socket服务器端(c++)

一个简单的服务器端的代码:

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

int main(int argc,char*argv[])
{
    int sockfd,new_fd;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    int sin_size,portnumber;
    char hello[]="Hello!Are you fine?";

    if(argc!=2)    {
        fprintf(stderr,"Usage:%s portnumber\n",argv[0]);
        exit(1);
    }
    if((portnumber=atoi(argv[1]))<0)    {
        fprintf(stderr,"Usage:%s portnumber should greater than zero\n",argv[0]);
        exit(1);
    }
    if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)    {
        fprintf(stderr,"Socket error:%s a\n",strerror(errno));
        exit(1);
    }

    bzero(&server_addr,sizeof(struct sockaddr_in));
    server_addr.sin_family=AF_INET;
    server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    server_addr.sin_port=htons(portnumber);

    if(bind(sockfd,(struct sockaddr*)(&server_addr),sizeof(struct sockaddr))==-1)
    {
        fprintf(stderr,"Bind error\n",strerror(errno));
        exit(1);
    }

    if(listen(sockfd,5)==-1)    {
        fprintf(stderr,"Listen error:%s\n",strerror(errno));
        exit(1);
    }

    while(1)    {
        sin_size = sizeof(struct sockaddr_in);
        if((new_fd=accept(sockfd,(struct sockaddr*)(&client_addr),(socklen_t*)(&sin_size)))==-1)
        {
            fprintf(stderr,"Accept error:%s\n",strerror(errno));

            exit(1);
        }
        fprintf(stderr,"Server get connnection from %s\n",inet_ntoa(client_addr.sin_addr));
        if(write(new_fd,hello,strlen(hello))==-1)        {
            fprintf(stderr,"Write error:%s",strerror(errno));
            exit(1);
        }
        close(new_fd);
    }
    close(sockfd);
    exit(0);
}

原文链接: https://www.cnblogs.com/crazyleeyang/archive/2012/04/13/2446207.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/47270

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午11:19
下一篇 2023年2月8日 下午11:20

相关推荐