#include "main.h" // $ ./prog02_udp_send_txt 127.0.0.1 2000 // hello //====================================================================== // MAIN //====================================================================== int main(int argc, char **argv) { int ok; int portNumber; int32_t value; char msg[0x100]; struct sockaddr_in toAddr; //---- check command line arguments ---- if(argc!=3) { fprintf(stderr,"usage: %s destination port\n",argv[0]); exit(1); } //---- extract destination IP address ---- struct hostent *host=gethostbyname(argv[1]); if(!host) { fprintf(stderr,"unknown host %s\n",argv[1]); exit(1); } in_addr_t ipAddress=*((in_addr_t *)(host->h_addr)); //---- extract destination port number ---- if(sscanf(argv[2],"%d",&portNumber)!=1) { fprintf(stderr,"invalid port %s\n",argv[2]); exit(1); } //---- create UDP socket ---- int udpSocket=socket(PF_INET,SOCK_DGRAM,0); if(udpSocket==-1) { perror("socket"); exit(1); } // ... allowing broadcast (optional) int on=1; ok = setsockopt(udpSocket,SOL_SOCKET,SO_BROADCAST,&on,sizeof(int)); if( ok == -1) { perror("setsockopt"); exit(1); } for(;;) { //---- read next line on standard input ---- if(!fgets(msg,0x100,stdin)) { break; } // [Control]+[d] --> EOF //---- extract 32-bit integer ---- if(sscanf(msg,"%d",&value)!=1) continue; //---- convert to network format 32-bit integer ---- value=htonl(value); //---- send message to the specified destination/port ---- toAddr.sin_family=AF_INET; toAddr.sin_port=htons(portNumber); toAddr.sin_addr.s_addr=ipAddress; ok = sendto(udpSocket,&value,4,0,(struct sockaddr *)&toAddr,sizeof(toAddr)); if( ok == -1){ perror("sendto"); exit(1); } } close(udpSocket); return 0; } //^^^^^^^^^^^^^^^^^^^^^^^^^^ EOF ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^