Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- void printconnerror()
- {
- switch (errno) {
- case ETIMEDOUT : printf("Connection timed out.\n"); break;
- case ECONNREFUSED : printf("Connection refused.\n"); break;
- case EHOSTDOWN : printf("Host down.\n"); break;
- case EHOSTUNREACH : printf("No route to the host.\n"); break;
- case ENETUNREACH : printf("Network unreachable.\n"); break;
- default: printf("errno = %d\n", errno);
- }
- }
- int main()
- {
- int sockfd,rec_sock,socknew, len,i,choix;
- struct sockaddr_in addr, recaddr;
- char buf[100],buf1[100],ip[22];
- int port;
- FILE* fichier = NULL;
- if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
- perror(": Can't get socket");
- exit(1);
- }
- addr.sin_addr.s_addr = INADDR_ANY;
- addr.sin_family = AF_INET;
- addr.sin_port = htons(4450);
- if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
- perror(": bind");
- exit(1);
- }
- printf("ip = %s, port = %d\n", inet_ntoa(addr.sin_addr), addr.sin_port);
- if (listen(sockfd, 5) < 0) {
- perror(": bind");
- exit(1);
- }
- rec_sock = accept(sockfd, (struct sockaddr *)(&recaddr), &len);
- if (rec_sock < 0) {
- perror(": accept");
- exit(1);
- }
- /* print the remote socket information */
- printf("remote machine = %s, port = %x, %x.\n", inet_ntoa(recaddr.sin_addr), recaddr.sin_port, ntohs(recaddr.sin_port));
- write(rec_sock, "connecter", 20);
- for (i=0; i<100; i++)
- buf[i] = '\0';
- read(rec_sock, buf, 99);
- printf("port aleatoire : %s\n", buf);
- // put client info in a txt file
- fichier = fopen("tmp.txt", "w");
- if (fichier != NULL)
- {
- fprintf(fichier,"Remote machine ip = %s Port = %s \n",inet_ntoa(recaddr.sin_addr),buf);
- fclose(fichier);
- strcpy(ip,inet_ntoa(recaddr.sin_addr));
- }
- printf("\n \n");
- port=atoi(buf);
- printf("%s \n",ip);
- printf("%d \n",port);
- printf("voulez vous se connecte au client\n");
- scanf("%d",&choix);
- if(choix==1)
- {
- if ((socknew = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
- perror(": Can't get socket");
- exit(1);
- }
- memset(&recaddr, 0, sizeof(struct sockaddr_in));
- recaddr.sin_family = AF_INET;
- recaddr.sin_port = htons(port);
- recaddr.sin_addr.s_addr = inet_addr(ip);
- //printf("%s \n",ntohs(recaddr.sin_port));
- //printf("%s \n",inet_ntoa(recaddr.sin_addr));
- if (connect(socknew, (struct sockaddr *)&recaddr, sizeof(recaddr)) < 0) {
- printconnerror();
- perror(": connect");
- exit(1);
- }
- for (i=0; i<100; i++)
- buf[i] = '\0';
- read(socknew, buf, 99);
- printf("Chaine = %s\n", buf);
- printf("Commande a executer \n");
- scanf("%s",&buf1);
- write(socknew,buf1,20);
- }
- sleep(20);
- exit(1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement