1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <string.h>
int main(int argc, char *argv[])
{ struct sockaddr_in fsin; int msock, ssock; char *service = "50500"; struct sockaddr_in sin; int alen; char pts[1000]; time_t now;
msock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
memset(&sin, '\0', sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons((unsigned short)atoi(service)); bind(msock, (struct sockaddr *)&sin, sizeof(sin));
listen(msock, 5);
while (1) { alen = sizeof(struct sockaddr); ssock = accept(msock, (struct sockaddr *)&fsin, (socklen_t *)&alen); time_t t = time(NULL); char ch[64] = {0}; char result[100] = {0}; strftime(ch, sizeof(ch) - 1, "%Y-%m-%d %H:%M:%S\n", localtime(&t)); memset(pts,0,sizeof(pts)); int c1 = recv(ssock, pts, 1000, 0);
unsigned int tem=fsin.sin_addr.s_addr; printf("收到消息: %s\n收到时间: %s客户端IP地址: %d.%d.%d.%d\n 客户端端口号:%d\n" ,pts,ch,(tem<<24)>>24,(tem<<16)>>24,(tem<<8)>>24,tem>>24,fsin.sin_port); char tempts[100]; strcpy(tempts,pts); tempts[strlen(pts)]='\0'; sprintf(pts,"\n内容: %s\n时间: %s客户端IP地址: %d.%d.%d.%d\n客户端端口号: %d\n", tempts,ch,(tem<<24)>>24,(tem<<16)>>24,(tem<<8)>>24,tem>>24,fsin.sin_port);
int cc = send(ssock, pts, strlen(pts), 0); } close(msock); }
|