#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main() { int ld,sd; struct sockaddr_in skaddr; struct sockaddr_in from; socklen_t addrlen, length; char buff[100],send_message[100]; int n; if ((ld = socket (PF_INET, SOCK_STREAM, 0))<0) { perror("Problem creating socket/n"); exit(1); } skaddr.sin_family = AF_INET; skaddr.sin_addr.s_addr = htonl (INADDR_ANY); skaddr.sin_port = htons(0); if(bind(ld,(struct sockaddr *)&skaddr, sizeof (skaddr))<0){ perror("Problem binding/n"); exit(0); } length = sizeof (skaddr); if (getsockname(ld, (struct sockaddr *)&skaddr, &length) <0) { perror("Error getsockname/n"); exit(1); } printf("The Server passive socket port number is %d/n", ntohs(skaddr.sin_port)); if (listen(ld,5)<0) { perror("Error calling listen/n"); exit(1); } while (1) { printf("Ready for a connection ... /n"); addrlen=sizeof(skaddr); if((sd = accept (ld, (struct sockaddr*) &from, &addrlen)) <0) { perror("Problem with accept call/n"); exit(1); } printf("Got a connect - processing .../n"); length = sizeof (skaddr); if (getsockname (sd, (struct sockaddr*)&skaddr, &length)<0) { perror ("Error getsockname/n"); exit(1); } printf("The active server port number is %d/n", ntohs (skaddr.sin_port)); printf("The active server IP ADDRESS is %s/n" ,inet_ntoa (skaddr.sin_addr)); printf("The client port number is %d/n", ntohs(from.sin_port)); printf("The client IP ADDRESS is %s/n",inet_ntoa(from.sin_addr)); while ((n=read(sd,buff,100))>0) { /* printf("%s/n","Client say:"); write (1,buff,n); printf("%s/n","Server say:"); fgets(send_message,100,stdin); write (sd,send_message,strlen(send_message)); */ write (sd,buff,n); } printf("Done with connection -closing/n/n/n"); close (sd); } }
|