逻辑上socket处于应用层与传输层之间。
ip,端口,协议,一起决定了网络的一个端点。
#include <iostream> #include "unp.h" int main(int argc, char** argv) { int sockfd; int n; char recvline[MAXLINE + 1]; struct sockaddr_in servaddr; if (argc != 2) { err_quit("usage: a.out <IPaddress>"); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { err_sys("socket error"); } bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(13); // daytime server if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) { err_quit("inet_pton error for %s", argv[1]); } if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) < 0) { err_sys("connect error"); } while ( (n = read(sockfd, recvline, MAXLINE)) > 0) { recvline[n] = 0; // null terminate if (fputs(recvline, stdout) == EOF) { err_sys("fputs error"); } } if (n < 0) { err_sys("read error"); } exit(0); }
ALL = daytimetcpcli daytimetcpsrv client server byteorder CFLAGS = -Wall -g all: ${ALL} daytimetcpcli.o: daytimetcpcli.cpp g++ ${CFLAGS} -c daytimetcpcli.cpp -I ../lib -o daytimetcpcli.o daytimetcpcli: daytimetcpcli.o g++ ${CFLAGS} daytimetcpcli.o ../libunp.a -I ../lib -o daytimetcpcli daytimetcpsrv.o: daytimetcpsrv.cpp g++ ${CFLAGS} -c daytimetcpsrv.cpp -I ../lib -o daytimetcpsrv.o daytimetcpsrv: daytimetcpsrv.o g++ ${CFLAGS} daytimetcpsrv.o ../libunp.a -I ../lib -o daytimetcpsrv client.o: client.cpp g++ ${CFLAGS} -c client.cpp -o client.o client: client.o g++ ${CFLAGS} client.o -o client server.o: server.cpp g++ ${CFLAGS} -c server.cpp -o server.o server: server.o g++ ${CFLAGS} server.o -o server byteorder.o: byteorder.cpp g++ ${CFLAGS} -c byteorder.cpp -I ../lib -o byteorder.o byteorder: byteorder.o g++ ${CFLAGS} byteorder.o -I ../lib -o byteorder clean: rm *.o ${ALL}
时间: 2024-10-23 13:59:28