The client uses the following socket or POSIX interface functions in this program example:
socket(): create socket
gethostbyname(): get the host name entry
sendto(): send a message to a socket
close(): close socket
Example: connectionless client
#include <stdio.h> #include <sys/socket.h> #include <ioctl.h> #include <signal.h> #include <netinet/in.h> #include <netdb.h> #define DATA " The sea is calm, the tide is full ..." #define ERROR_EXIT(M) perror(M); exit(1) #define TESTPORT 2222 int main(int argc, char **argv) { int sock; struct sockaddr_in to; struct hostent *hp; /* Create the client socket to be sent from. */ if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { ERROR_EXIT("socket"); } /* Construct the name of the server socket to be sent to. */ if ((hp =gethostbyname(argv[1])) == NULL) { fprintf(stderr, "%s: unknown host\n", argv[1]); exit(1); } memcpy((char *)&to.sin_addr, (char *)hp->h_addr,hp->h_length); to.sin_family = AF_INET; to.sin_port = htons(TESTPORT); /* Send message. */ if (sendto(sock, DATA, sizeof DATA, 0, (struct sockaddr *)&to, sizeof to) < 0) { ERROR_EXIT("sendto"); } close(sock); return 0; }
The following steps are executed in the program example:
The socket() function creates a communications endpoint (client socket) and a corresponding descriptor.
- The IP address of the server is determined with gethostbyname(). The computer name is passed as a parameter when the program is called.
Then the server address structure is initialized.
- The sendto() function sends a datagram from the client socket to the server socket. It returns the number of characters sent.
The close() function closes the client socket.
The example program is only valid for the communications domain AF_INET. If it is modified according to the information in " Socket addressing " and " Creating a socket ", it is also valid for the AF_INET6 domain. Please also make sure that you use the getaddrinfo() or getipnodebyname() functions instead of gethostbyname() .