Linux网络编程之TCP通信
客户端代码
client.cpp
#include <stdlib.h>#include <sys/types.h>#include <netinet/in.h>#include <sys/socket.h>#include <arpa/inet.h>#include <unistd.h>#include <stdio.h>int main() {//用 SOCK_STREAM 标识建立 TCP连接int sockfd = socket(AF_INET, SOCK_STREAM, 0);struct sockaddr_in server_addr;server_addr.sin_family = AF_INET;server_addr.sin_port = htons(1991); //需要转化字节序//需要把点分10进制的地址转化/* * Name: inet_addr Prototype: uint32_t inet_addr (const char *name) Description: This function converts the IPv4 Internet host address name from the standard numbers-and-dots notation into binary data. If the input is not valid, inet_addr returns INADDR_NONE. This is an obsolete interface to inet_aton, described immediately above. It is obsolete because INADDR_NONE is a valid address (255.255.255.255), and inet_aton provides a cleaner way to indicate error return. */server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");/*绑定*/bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));/* * Name: listen Prototype: int listen (int socket, int n) Description: The listen function enables the socket socket to accept connections, thus making it a server socket. The argument n specifies the length of the queue for pending connections. When the queue fills, new clients attempting to connect fail with ECONNREFUSED until the server calls accept to accept a connection from the queue. The listen function returns 0 on success and -1 on failure. The following errno error conditions are defined for this function: */listen(sockfd, 10);char ch;struct sockaddr_in client_addr;socklen_t len = sizeof(client_addr);//socklen_t len = 0;while(1){int client_sockfd;printf("server waiting: \n");client_sockfd = accept(sockfd, (struct sockaddr *) &client_addr, &len);//只读取一个字符read(client_sockfd, &ch, 1);printf("get char from client: %c\n", ch);++ch;//把该字符 +1后再发回给客户端write(client_sockfd, &ch, 1);close(client_sockfd);}//printf("%0x", server_addr.sin_addr.s_addr);return 0;}