欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

Linux网络编程(一):一个简单的socket程序

程序员文章站 2022-03-09 22:41:15
服务器: 客户端: 参考: 《UNIX网络编程 - 卷1:套接字联网API》 ......

服务器:

/*
 *tcp_server.c
 */

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#define ser_port 8000
#define max_line 1024

int main(int argc, char **argv)
{
    int listenfd, connfd;
    struct sockaddr_in servaddr, cliaddr;
    socklen_t cliaddr_len;
    char buff[max_line];
    
    listenfd = socket(af_inet, sock_stream, 0);
    
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = af_inet;
    servaddr.sin_addr.s_addr = htonl(inaddr_any);
    servaddr.sin_port = htons(ser_port);
    
    bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    
    listen(listenfd, 20);
    
    while(1)
    {
        cliaddr_len = sizeof(cliaddr);
        connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
        printf("receive from %s at port %d\n", inet_ntop(af_inet, &cliaddr.sin_addr, buff, sizeof(buff)), ntohs(cliaddr.sin_port));
        
        close(connfd);
    }

    return 0;
}

客户端:

/*
 *tcp_client.c
 */

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>

#define ser_port 8000
#define max_line 1024

int main(int argc, char **argv)
{
    int sockfd;
    struct sockaddr_in servaddr;

    sockfd = socket(af_inet, sock_stream, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = af_inet;
    inet_pton(af_inet, "127.0.0.1", &servaddr.sin_addr);
    servaddr.sin_port = htons(ser_port);
    
    if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        printf("connect error:%s\n", strerror(errno));
    }
    
    return 0;
}