C/C++培训
美国上市C/C++培训机构

400-111-8989

热门课程

C语言培训:简单的客户端和服务端程序

  • 时间:2015-01-14
  • 发布:达内
  • 来源:达内

  服务端程序

#include

#include

#include

#include

#include

#include

#include

#include

#define PORT 1234

#define BACKLOG 1

main()

{

int listenfd,connectfd;

struct sockaddr_in server;

struct sockaddr_in client;

int sin_size;

if((listenfd = socket(AF_INET,SOCK_STREAM,0)) == -1){

perror("Creating socket failed.");

exit(1);

}

int opt = SO_REUSEADDR;

setsockopt(listenfd , SOL_SOCKET, SO_REUSEADDR , &opt, sizeof(opt));

bzero(&server,sizeof(server));

server.sin_family=AF_INET;

server.sin_port=htons(PORT);

server.sin_addr.s_addr = htonl(INADDR_ANY);

if(bind(listenfd,(struct sockaddr *)&server,sizeof(struct sockaddr)) == -1){

perror("Bind error.");

exit(1);

}

if(listen(listenfd ,BACKLOG) == -1){

perror("listen() error \n");

exit(1);

}

sin_size = sizeof(struct sockaddr_in);

if((connectfd = accept(listenfd,(struct sockaddr *) &client, &sin_size)) == -1){

perror("accept() error \n");

exit(1);

}

printf("You got a connection from %s \n" ,inet_ntoa(client.sin_addr));

send(connectfd,"welcome to my server.\n",22,0);

close(connectfd);

close(listenfd);

}
    客户端程序

#include

#include

#include

#include

#include

#include

#include

#define PORT 1234

#define MAXDATASIZE 100

int main(int argc,char *argv[])

{

int fd,numbytes;

char buf[MAXDATASIZE];

struct hostent *he;

struct sockaddr_in server;

if(argc !=2){

printf("Usage: %s \n",argv[0]);

exit(1);

}

if((he = gethostbyname(argv[1]))==NULL){

/*调用gethostbyname()函数*/

printf("gethostbyname() error \n");

exit(1);

}

if((fd=socket(AF_INET,SOCK_STREAM,0)) == -1){

/*调用socket()函数*/

printf("socket() error \n");

exit(1);

}

bzero(&server,sizeof(server));

server.sin_family=AF_INET;

server.sin_port=htons(PORT);

server.sin_addr=*((struct in_addr *)he -> h_addr);

if(connect(fd,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1){/*调用connect()函数*/

printf("connect() error \n");

exit(1);

}

if((numbytes=recv(fd,buf,MAXDATASIZE,0))== -1){

/*调用recv()函数*/

printf("recv() error\n");

exit(1);

}

buf[numbytes] = '\0';

printf("Server Message:%s \n",buf);/*显示服务器端的欢迎信息*/

close(fd);

}

上一篇:C++实例海明距离
下一篇:C++单元测试--打桩测试

C++学习笔记之win32平台日志类

C++进阶-类型转换,你看我就够了

C语言结构体(struct)知识点详解

达内C/C++培训:C++异常处理机制知识点总结

选择城市和中心
贵州省

广西省

海南省