In this assignment two hosts will communicate with each other using UDP. While the idea is that there are two programs on two different hosts, it is possible to run the two programs on the same machine.
There are two types of hosts (and hence two programs), client and server.
More specifically,
The server must
The client must
int UDPSock; UDPSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
This will make the socket receive data from a particular port. Also, when data is sent with this socket, the source port of the data will be this port.
For the server, define the port:
int UDPPort = 10000;
For the client, define the port:
int UDPPort = 10001;
Now we bind the socket to this port as follows
struct sockaddr_in My; memset(&My,0,sizeof(My));// clear memory My.sin_family = AF_INET; // must be this My.sin_addr.s_addr = htonl(INADDR_ANY); My.sin_port = htons(UDPPort); // the port on this host /* BIND THE SOCKET TO Port */ int ret=bind(UDPSock, (struct sockaddr *)&My, sizeof(struct sockaddr)); printf("bind returned %d if not zero, then there was a problem\n",ret);
char ToIPAddress[80]; sprintf(ToIPAddress,"128.4.132.43"); // put the IP of the server int WriteToPort = 10000; // the client will write to 10000 struct sockaddr_in to; memset(&to,0,sizeof(to)); to.sin_addr.s_addr = inet_addr(ToIPAddress); to.sin_family = AF_INET; to.sin_port = htons(WriteToPort); // set port address
char pkt[300]; sprintf(pkt,"hello there\n"); ret = sendto(UDPSock, (char *)pkt, sizeof(pkt), 0, (struct sockaddr *)&to, sizeof(struct sockaddr)); printf("sendto returned %d it should be the number of bytes sent \n",ret); fd_set readFd; timeval SelectTime; SelectTime.tv_sec = 2;// wait 2 seconds SelectTime.tv_usec=0; FD_ZERO(&readFd); FD_SET(UDPSock,&readFd); ret = Selec(255,&readFd,NULL,NULL,&SelectTime); if (FD_ISSET(UDPSock, &readFD)==1) { ret = recv(UDPSock, (char *)pkt, 300,0); printf("received: %s",pkt); } else { printf("no response from %s\n",ToIPAddress); }
char buf[300]; struct sockaddr_in from; int len = sizeof(struct sockaddr); ret = recvfrom(UDPSock, (char *)buf, 300, 0,(struct sockaddr *)&from,(socklen_t *)&len); printf("recv returned %d\n",ret); printf("received data from %s from port %d\n",inet_ntoa(from.sin_addr),ntohs(from.sin_port)); printf("%s",buf); sprintf(buf,"go away\n"); struct sockaddr_in to; memset(&to,0,sizeof(to)); to.sin_addr.s_addr = from.sin_addr.s_addr; to.sin_family = AF_INET; to.sin_port = from.sin_port; // set port address ret = sendto(UDPSock, (char *)buf, 300, 0, (struct sockaddr *)&to, sizeof(struct sockaddr)); printf("sendto returned %d\n",ret);