I sure thought I was familiar with the Sockets API but I dont understand why the server code doesn't print "got a connection from [ ip addr && port]" string until something is written on the socket from the client. I've used the library for a few things in the past but perhaps there is something I'm missing here.
server.c
client.cCode:#include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <string.h> #include <errno.h> void error(const char *err_str){ printf("%s: %s\n",err_str, strerror(errno)); exit(-1); } int main(int argc, char **argv){ if(argc != 2){ printf("Usage: %s <port>\n", argv[0]); exit(-1); } int listen_fd, accept_fd, nread, port; socklen_t length; char buffer[32], ipv4[INET_ADDRSTRLEN]; struct sockaddr_in server, client; if((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) <= 0) error("socket()"); bzero(&server, sizeof(server)); bzero(&client, sizeof(client)); server.sin_family = AF_INET; server.sin_port = htons(atoi(argv[1])); server.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(listen_fd, (struct sockaddr *)&server, sizeof(server)) == -1) error("bind()"); listen(listen_fd, 10); for(;;){ length = sizeof(client); accept_fd = accept(listen_fd,(struct sockaddr *)&client, &length); inet_ntop(AF_INET, &client.sin_addr, ipv4, INET_ADDRSTRLEN); port = ntohs(client.sin_port); printf("*************** Got a connection from %s %u **********************",ipv4,port); while(nread = read(accept_fd, buffer, sizeof(buffer))){ buffer[nread] = 0; fputs(buffer,stdout); } close(accept_fd); fputs("**************** Connection closed *********************", stdout); } return 0; }
Code:#include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <string.h> #include <errno.h> void error(const char *err_str){ printf("%s: %s\n", err_str, strerror(errno)); exit(-1); } int main(int argc, char **argv){ if(argc != 3){ printf("Usage: %s <ip address> <port number>\n",argv[0]); exit(-1); } int sock_fd, nread, nleft, nwritten; char buffer[32]; struct sockaddr_in server; if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) <= 0) error("socket()"); bzero(&server, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(atoi(argv[2])); inet_pton(AF_INET, argv[1], &server.sin_addr); if(connect(sock_fd, (struct sockaddr *)&server, sizeof(server)) < 0) error("connect()"); fputs("************ Got a connection from remote host *************\n", stdout); fgets(buffer, sizeof(buffer), stdin); while(nwritten = write(sock_fd, buffer, strlen(buffer))){ bzero(&buffer, sizeof(buffer)); fgets(buffer,sizeof(buffer), stdin); } close(sock_fd); return 0; }



LinkBack URL
About LinkBacks



