linux Socket简单编程实例

 服务端

网络编程中服务端接受连接的套接字创建过程如下:

1.调用socket函数创建套接字

2.调用bind函数分配IP地址和端口号

3.调用listen函数转为可接收请求状态

4.调用accept函数受理连接请求

#include 
#include 
#include           
#include 
#include 
#include 
#include 

void error_handing(char* messgae);

void error_handing(char* message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char*argv[])
{
    int serv_sock; // 服务端socket
    int clnt_sock;
    struct sockaddr_in serv_addr;
    struct sockaddr_in clnt_addr;

    char message[] = "helloworld!";

    if (argc != 2)
    {
        printf("Usage: %s\n", argv[0]);
        exit(1);
    }
    serv_sock = socket(PF_INET, SOCK_STREAM, 0);
    if (serv_sock == -1)
    {
        error_handing("socket() error");
    }
    bzero(&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port =  htons(atoi(argv[1]));

    if(bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1)
    {
        error_handing("bind() error");
    }

    if(listen(serv_sock, 5) == -1)
    {
        error_handing("listen() error");
    }
    socklen_t clnt_addr_len = sizeof(clnt_addr);
    clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_len);
    if (clnt_sock == -1)
    {
        error_handing("accept() error");
    }
    
    write(clnt_sock, message, sizeof(message));

    close(serv_sock);
    close(clnt_sock);

    return 0;
}

客户端

1.创建客户端套接字

2.连接服务端

#include 
#include 
#include           
#include 
#include 
#include 
#include 

void error_handing(char* messgae);

void error_handing(char* message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char*argv[])
{
    int sock;
    struct sockaddr_in serv_addr;
    char message[30];
    int str_len;

    if(argc != 3)
    {
        printf("Usage : %s\n", argv[0]);
        exit(1);
    }
    sock = socket(PF_INET, SOCK_STREAM, 0);
    if(sock == -1)
    {
        error_handing("socket() error");
    }
    bzero(&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
    serv_addr.sin_port = htons(atoi(argv[2]));

    if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1)
    {
        error_handing("connect() error");
    }
    str_len = read(sock, message, sizeof(message)-1);
    if (str_len == -1)
    {
        error_handing("read() error");
    }
    printf("message from server: %s\n", message);
    close(sock);
    
    return 0;
}

运行结果

linux Socket简单编程实例_第1张图片

你可能感兴趣的:(TCP/IP,linux,服务器,运维)