/*UDP SERVER*/ #include <sys/socket.h> /* for bind socket accept */ #include /* for close() */ #include <arpa/inet.h>/* for inet_Addr etc*/ #include <string.h> /* for string and memset etc */ #include /* for standard input output */ using namespace std; int main() { int iSockFd=-1; int iLength=0; struct sockaddr_in servAddr,cliAddr; char buff[1024]; iSockFd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); memset(&servAddr,0,sizeof(servAddr)); memset(&cliAddr,0,sizeof(cliAddr)); servAddr.sin_family=AF_INET; servAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); servAddr.sin_port=htons(42001); int cliAddrLen=sizeof(struct sockaddr_in); int bindRet=bind(iSockFd,(struct sockaddr*)&servAddr,sizeof(servAddr)); cout <<"Bind returned "<
} ================================================================== UDP CLIENT ================================================================== /*UDP CLIENT*/ #include #include #include #include #include #include #include #include #include
<stdio.h> <stdlib.h> <sys/types.h> <sys/socket.h> <arpa/inet.h>
/* /* /* /* /* /* /* /*
standard C i/o facilities */ needed for atoi() */ defines STDIN_FILENO, system calls,etc */ system data type definitions */ socket specific definitions */ INET constants and stuff */ IP address conversion stuff */ gethostbyname */
#define MAXBUF 1024*1024 int main( int argc, char **argv ) { int sk; struct sockaddr_in server; struct hostent *hp; char buf[MAXBUF];
int buf_len; int n_sent; int n_read; if ((sk = socket( PF_INET, SOCK_DGRAM, 0 )) < 0) { printf("Problem creating socket\n"); exit(1); } server.sin_family=AF_INET; server.sin_addr.s_addr=inet_addr("127.0.0.1"); /* establish the server port number - we must use network byte order! */ server.sin_port = htons(42001); memset(buf,65,1); /* send it to the echo server */ n_sent = sendto(sk,buf,1,0, (struct sockaddr*) &server,sizeof(server)); if (n_sent<0) { perror("Problem sending data"); exit(1); } return(0); } -------------------------------------------------------------------