63 lines
1.7 KiB
C
63 lines
1.7 KiB
C
|
|
|
|
#include "../basic.h"
|
|
#include <time.h>
|
|
|
|
int main(int argc, char **argv) {
|
|
int listenfd, connfd, n;
|
|
struct sockaddr_in servaddr;
|
|
|
|
|
|
if (argc != 2 ){
|
|
printf("usage: daytimesrv <porta>\n");
|
|
exit(0);
|
|
}
|
|
if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
|
|
printf("socket error\n");
|
|
exit(0);
|
|
}
|
|
bzero(&servaddr, sizeof(servaddr));
|
|
servaddr.sin_family = AF_INET;
|
|
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); /* wildcard address */
|
|
servaddr.sin_port = htons(atoi(argv[1])); /* server port */
|
|
|
|
if( (bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr))) < 0){
|
|
printf("bind error\n"); exit(0);
|
|
}
|
|
if( listen(listenfd, 5) < 0 )
|
|
{ printf("listen error\n");
|
|
exit(0);
|
|
}
|
|
|
|
char client_address_redeable[INET_ADDRSTRLEN];
|
|
short client_port_redeable;
|
|
|
|
struct sockaddr_in client_address_struct;
|
|
unsigned int client_address_struct_size = sizeof(client_address_struct);
|
|
|
|
struct sockaddr_in server_struct_to_send;
|
|
unsigned int server_struct_to_send_size = sizeof(server_struct_to_send);
|
|
|
|
|
|
|
|
for ( ; ; ) {
|
|
if( (connfd = accept(listenfd, (struct sockaddr *) &client_address_struct, &client_address_struct_size)) < 0)
|
|
{ printf("accept error\n");
|
|
exit(0);
|
|
}
|
|
|
|
inet_ntop(AF_INET, &(client_address_struct.sin_addr), client_address_redeable, INET_ADDRSTRLEN);// get client ip
|
|
client_port_redeable = ntohs(client_address_struct.sin_port);// get client port
|
|
|
|
fprintf (stdout,"%s%c%hu\n",client_address_redeable,':',client_port_redeable);
|
|
|
|
|
|
|
|
getsockname (connfd, (struct sockaddr *) &server_struct_to_send, &server_struct_to_send_size);
|
|
write (connfd,&server_struct_to_send, server_struct_to_send_size);
|
|
|
|
|
|
close(connfd);
|
|
}
|
|
}
|