socket_1

  1. linux socket server

linux socket server


#include<sys/socket.h>
#include<unistd.h>
#include <netdb.h>
#include<stdlib.h>
#include<netinet/in.h>
#include <sys/types.h>
#include <netinet/in.h>
#include<stdio.h>
#include <arpa/inet.h>
int main(int argc, char const *argv[])
{

    int sockfd,client_sockfd;

    struct sockaddr_in my_addr,client_addr;

    int addr_len;

    my_addr.sin_family = AF_INET;

    my_addr.sin_port  = htons(9000);

    my_addr.sin_addr.s_addr=INADDR_ANY;

    sockfd = socket(AF_INET,SOCK_STREAM,0);

    bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr));    


    //max queue 10
    listen(sockfd,10);

    addr_len = sizeof(struct sockaddr);

    while (1)
    {

        printf("server is waiting for client to connect:\n");


        socklen_t client_size;

        client_sockfd = accept(sockfd, (struct sockaddr *)&client_addr,&client_size);

        printf("Client ip address=%s\n",inet_ntoa(client_addr.sin_addr));

        char *hello = "hello";

        send(client_sockfd,hello,sizeof(hello),0);

        printf("disconnect the client request\n");

        close(client_sockfd);

    }
    
    close(sockfd);

    return 0;
}

打完收工


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 ggchzzz@163.com

文章标题:socket_1

字数:168

本文作者:ggchzzz

发布时间:2023-12-23, 02:04:40

最后更新:2023-12-23, 02:14:30

原始链接:https://anska.info/post/5.html

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

github