客户端: #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #define MAXLINE 2000 int main(int argc, char **argv) { int sockfd, n; char recvline[MAXLINE + 1]; struct sockaddr_in servaddr; if(argc != 2) printf("usage : a.out <IP address> "); if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) printf("socket error"); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(13); if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) printf("inet_pton error for %s", argv[1]); if(connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) printf("connect error"); while((n = read(sockfd, recvline, MAXLINE)) > 0) { recvline[n] = 0; if(fputs(recvline, stdout) == EOF) printf("fputs error"); } if(n < 0) printf("read error"); exit(0); }
#include <time.h> #include <string.h> #include <unistd.h> #include <netinet/in.h> #include "mysocket.h" #define MAXLINE 2000 int main(int argc, char *argv[]) { int listenfd, connfd; struct sockaddr_in servaddr; char buff[MAXLINE]; time_t ticks; listenfd = Socket(AF_INET, SOCK_STREAM, 0); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(13); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); listen(listenfd, LISTENQ); while(1) { connfd = accept(listenfd, (struct sockaddr *)NULL, NULL); ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); write(connfd, buff, strlen(buff)); close(connfd); } }
#ifndef _MYSOCKET_H_ #define _MYSOCKET_H_ #include <sys/socket.h> #include <stdio.h> #define LISTENQ 100 int Socket(int family, int type, int protocol) { int n; if((n = socket(family, type, protocol)) < 0) printf("socket error"); return n ; } #endif
客户端运行:time 127.0.0.1
服务器端运行: timeserer &
相关命令: kill
ps -ax 查看当前搜有运行程序
05-12
02-14