C语言中网络编程的简单操作

来源:爱站网时间:2021-01-07编辑:网友分享
网络编程通俗来讲就是信息的接收,而传输的作用也是很重要的,在发送中通常是使用指定协议集合的,那么C语言中网络编程的简单操作,大家都清楚吗?爱站技术频道是非常好的选择。

网络编程通俗来讲就是信息的接收,而传输的作用也是很重要的,在发送中通常是使用指定协议集合的,那么C语言中网络编程的简单操作,大家都清楚吗?爱站技术频道是非常好的选择。

c语言网络编程-标准步骤

server.c

 

 

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

#define PORT 4444
#define BACKLOG 5

int main(int argc, char *argv[]) {
    int sock_fd, new_fd;
    struct sockaddr_in server_addr, client_addr;
    int sin_size;
    int nbytes;
    int on = 1;
    char buffer[1024];

    if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    memset(&server_addr, 0, sizeof(struct sockaddr_in));
    server_addr.sin_family      = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port        = htons(PORT);

    if (bind(sock_fd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1) {
        perror("bind");
        exit(1);
    }

    if (listen(sock_fd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    printf("Server start... \n");

    while (1) {
        sin_size = sizeof(struct sockaddr_in);
        if ((new_fd = accept(sock_fd, (struct sockaddr *)(&client_addr), &sin_size)) == -1) {
            perror("accept");
            exit(1);
        }

        printf("Server get connection from %s\n", inet_ntoa(client_addr.sin_addr));
        if ((nbytes = read(new_fd, buffer, 1024)) == -1) {
            perror("read");
            exit(1);
        }
        buffer[nbytes] = '\0';
        printf("Server received: %s\n", buffer);
        close(new_fd);
    }

    return 0;
}

 

client.c

 

 

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

#define PORT 4444

int main(int argc, char *argv[]) {
    int sock_fd;
    struct sockaddr_in server_addr;
    struct hostent *host;
    char buffer[1024];

    if (argc         perror("Need hostname");
        exit(1);
    }

    if ((host = gethostbyname(argv[1])) == NULL) {
        perror("gethostbyname");
        exit(1);
    }

    if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    memset(&server_addr, 0, sizeof(struct sockaddr_in));
    server_addr.sin_family  = AF_INET;
    server_addr.sin_port    = htons(PORT);
    server_addr.sin_addr    = *((struct in_addr *)host->h_addr);

    if (connect(sock_fd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1) {
        perror("connect");
        exit(1);
    }

    printf("Please input something:\n");
    fgets(buffer, 1024, stdin);
    write(sock_fd, buffer, strlen(buffer));
    close(sock_fd);

    return 0;
}

好了,关于C语言中网络编程的简单操作,爱站技术频道小编的分享到这里就结束了,更多的专业知识,随时欢迎您来到js.aizhan.com吧!

上一篇:C语言中的内存的记忆分析

下一篇:C++中函数指针的学习详解

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载