1 /* datagram.c - datagram sockets server
13 /* socket and bind stuff */
14 #include <sys/types.h>
15 #include <sys/socket.h>
18 #include <netinet/in.h>
21 #include <arpa/inet.h>
35 int main(int argc, char *argv[]) {
36 int send_fd,broadcast_on;
37 struct sockaddr_in local_addr, remote_addr;
38 socklen_t remote_addr_len,optlen;
39 int send_bytes, read_bytes;
40 unsigned char buf[MAX_BUF];
43 printf("usage: %s <target-ip/broadcast-addr> <port>\n",argv[0]);
47 if((send_fd=socket(AF_INET,SOCK_DGRAM,0)) == -1) {
48 printf("can't open socket.\n");
53 optlen=sizeof(broadcast_on);
54 if((setsockopt(send_fd,SOL_SOCKET,SO_BROADCAST,&broadcast_on,optlen))==-1)
58 memset(&local_addr,0,sizeof(local_addr));
59 local_addr.sin_family=AF_INET;
60 local_addr.sin_port=htons(atoi(argv[2]));
61 local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
63 if(bind(send_fd,(struct sockaddr *)&local_addr,sizeof(local_addr))==-1) {
64 printf("unable to bind on port %d.\n",atoi(argv[2]));
69 remote_addr_len=sizeof(remote_addr);
70 memset(&remote_addr,0,sizeof(remote_addr));
71 remote_addr.sin_family=AF_INET;
72 remote_addr.sin_port=htons(atoi(argv[2]));
73 remote_addr.sin_addr.s_addr=inet_addr(argv[1]);
78 read_bytes=read(0,buf,sizeof(buf));
79 send_bytes=sendto(send_fd,buf,read_bytes,0,(struct sockaddr *)&remote_addr,remote_addr_len);
86 printf("connection closed ...\n");
87 printf("%d from %d total bytes sent.\n",send_bytes,read_bytes);