OpenSource For You

The source code

-

Now please refer to the downloaded source code. The socket function returns a socket descriptor (IPv4, SOCK_ DGRAM(UDP)), referred to by the variable sd. An address structure struct sockaddr_in (whose declaratio­n is in the file / usr/include/netinet/in.h in Linux) is needed. It's declaratio­n is available in the source code by inclusion of <netinet/in.h>.

In the client code, you need to populate this address structure (the serveraddr­ess variable) with the address family, the server’s IP address, and the port number. Note that this needs to be populated in the big-endian order, so use functions/macros like htons and inet_addr— htons(atoi(argv[2])), which transform the string the user passes as the command-line argument into a big-endian short integer. Similarly, inet_addr(argv[1]) transforms the IP address command-line argument into a 32-bit IPv4 address in the big-endian order. serveraddr­ess.sin_family = Ac_INET; serveraddr­ess.sin_port = htons(atoi(argv[2]));//PORT NO serveraddr­ess.sin_addr.s_addr = inet_addr(argv[1]);//AaaRESS

I used the functions recvfrom and sendto to receive and send UDP datagrams respective­ly. The sendto function prototype is as follows: ssi]HBW sHnGWR(inW sRFNIG, FRnsW YRiG *EuI, si]HBW OHn, inW flDgs,

const struct sockaddr *dest_addr, socklen_t addrlen);

The first argument is the socket descriptor, the second is the array from where to send data, and the third is the number of bytes to send. We have the fourth argument ( flDgs) as 0. This supports a few options, which you can learn from the manual page. The fifth argument is the address structure, which needs to be populated (in the client, it is populated with the server’s IP address and port number). The sixth argument is the size of this address structure.

Let us now understand the recvfrom function. Its prototype is as shown below: ssi]HBW UHFYIURP(inW s, YRiG *EuI, si]HBW OHn, inW flDgs, sWUuFW sock-

addr *from, socklen_t *fromlen);

The first three arguments are, respective­ly, the socket descriptor, the array where the received data is to be stored, and the length of that array. The fourth is the flDgs argument,

Newspapers in English

Newspapers from India