if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) <0){ perror("socket"); exit(1); }Read the man pages of system calls carefully and make sure you understand the meaning of all the return values.
cliAddrLen = sizeof(cliAddr); if ( (n = recvfrom(sd, (char*) data, sizeof(data), 0, &cliAddr, &cliAddrLen)) < 0 ) { ... }The cliAddr is just like a buffer you pass to the system requesting it to be filled in. You need to tell the system how large the buffer is, right? And since recvfrom() will change its value, it is better to set it every time recvfrom() is called.
struct hostent* server; struct sockaddr_in destAddr; /* argv[1] is "sun13.cs.wisc.edu" */ if ( (server = gethostbyname(argv[1])) == NULL ) { fprintf(stderr, "Cannot get address for host %s\n", argv[1]); exit(1); } memcpy(&(destAddr.sin_addr.s_addr), server->h_addr, server->h_length);Example of using inet_addr():
struct sockaddr_in destAddr; destAddr.sin_addr.s_addr = inet_addr("128.105.40.13");Example of using inet_ntoa():
// if added to the above inet_addr() code, this would print "128.105.40.13": // char *s = inet_ntoa(destAddr.sin_addr); printf("dotted decimal address is %s\n", s);