/* * Example of server using UDP protocol. */ #include "inet.h" #include #include int sigflag = 0; // sigflag == 1 if an I/O occurs int main(int argc,char *argv[]) { int sockfd; struct sockaddr_in serv_addr; void serv_act(int sockfd); /* * Open a UDP socket (an Internet datagram socket) */ if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) err_dump("server: can't open datagram socket"); /* * Bind our local address so that the client can send to us. */ bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(SERV_UDP_PORT); if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) err_dump("server: can't bind local address"); serv_act(sockfd); return 0; } /* * Read a datagram from a connectionless socket and write it back to * the sender. */ #define MAXMESG 2048 void serv_act(int sockfd) { struct sockaddr *pcli_addr; struct hostent *host_info; int maxclilen; int n, clilen; int client_port = -1; char mesg[MAXMESG]; void sigio_func(); // signal handler void process(); // user application int i; pcli_addr = new (struct sockaddr); maxclilen = sizeof(struct sockaddr); host_info = new (struct hostent); /* interrupt handler */ /* signal(SIGIO,sigio_func); */ /* * set up the socket so it is non-blocking */ /* if (fcntl(sockfd, F_SETOWN, getpid()) < 0) err_dump("F_SETOWN error"); if (fcntl(sockfd, F_SETFL, FASYNC) < 0) err_dump("F_SETFL FASYNC error"); for ( ; ; ) { while (sigflag == 0) process(); */ while (1) { clilen = maxclilen; n = recvfrom(sockfd, mesg, MAXMESG, 0, pcli_addr, (socklen_t*)&clilen); if (n < 0) err_dump("dg_echo: recvfrom error"); host_info = gethostbyaddr((char *)&(((struct sockaddr_in *)pcli_addr)->sin_addr.s_addr), sizeof (struct in_addr), AF_INET); client_port = ((struct sockaddr_in *)pcli_addr)->sin_port; printf(" client port number : %d\n", client_port); if (host_info != NULL) { printf(" hostname %s\n",host_info->h_name); /* print all aliases */ char *ptr; while ((ptr = *(host_info->h_aliases)) != NULL) { printf(" alias: %s\n", ptr); host_info->h_aliases ++; } printf(" addr type = %d, addr length = %d\n", host_info->h_addrtype, host_info->h_length); /* print IP address */ struct in_addr *adptr; while ((adptr = (struct in_addr *)(*(host_info->h_addr_list)++)) != NULL) { printf(" Internet address: %s\n", inet_ntoa(*adptr)); } } // if (host_info != NULL) if (sendto(sockfd, mesg, n, 0, pcli_addr, clilen) != n) err_dump("dg_echo: sendto error"); } /* sigflag -= 1; // decrease the number of connections } */ } void sigio_func() // signal handler { sigflag += 1; // increase the number of connections cout << " sig " << sigflag << '\n'; } void process() { int i; cout << " input a number \n"; cin >> i; }