64,670
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <memory>
#include <arpa/inet.h>
#include "error.h"
int main()
{
int sockfd,client_fd;/*sockfd: monitor socket; client_fd:data transmission socket*/
struct sockaddr_in my_addr;/*local host address message*/
struct sockaddr_in remote_addr;/*client address message*/
int ret;
do
{
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
ret=SOCKER_GREAT_ERROR;
break;
}
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVERPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
memset(my_addr.sin_zero,0,sizeof(my_addr.sin_zero));
if(bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr))==-1)
{
ret=BIND_ERROR;
break;
}
if(listen(sockfd,BACKLOG)==-1)
{
ret=LISTEN_ERROR;
break;
}
while(1)
{
socklen_t sin_size=sizeof(struct sockaddr);
if((client_fd=accept(sockfd,(struct sockaddr*)&remote_addr,&sin_size))==-1)
{
ret=ACCEPT_ERROR;
break;
}
printf("received a connection from %s\n", inet_ntoa(remote_addr.sin_addr));
if (!fork())
{
if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
{
ret=SEND_ERROR;
}
close(client_fd);
exit(0);
}
}
}while(0);
if(0!=ret)
printf("run error with %d\n",ret);
return ret;
}
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <memory>
#include <arpa/inet.h>
#include "error.h"
#include <netdb.h>
int main(int argc,char *argv[])
{
int ret;
do
{
int sockfd,recvdytes;
char buf[MAXDATASIZE];
hostent *host;
struct sockaddr_in serv_add;
if (argc < 2)
{
printf("Please enter the server's hostname!\n");
ret=ERROR_PARA;
break;
}
if((host=gethostbyname(argv[1]))=NULL)
{
ret=ERROR_GETHOSTNAME;
break;
}
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
ret=SOCKER_GREAT_ERROR;
break;
}
serv_add.sin_family=AF_INET;
serv_add.sin_port=htons(SERVERPORT);
serv_add.sin_addr = *((struct in_addr *)host->h_addr);
memset(serv_add.sin_zero,0,sizeof(serv_add.sin_zero));
if(connect(sockfd,(struct sockaddr*)&serv_add,sizeof(struct sockaddr))==-1)
{
ret=CONNECT_ERROR;
break;
}
if(recvdytes=recv(sockfd,buf,MAXDATASIZE,0)==-1)
{
ret=RECV_ERROR;
break;
}
buf[recvdytes]='\0';
printf("recvytes=%s",buf);
close(sockfd);
}while(0);
printf("run error with %d\n",ret);
return ret;
}
#define MAXDATASIZE 100
#define ERROR_PARA 1000
#define ERROR_GETHOSTNAME 1006
#define SERVERPORT 3333 /*服务器监听端口号*/
#define BACKLOG 10 /*max connet number*/
#define BIND_ERROR 1001
#define LISTEN_ERROR 1002
#define ACCEPT_ERROR 1003
#define SEND_ERROR 1004
#define SOCKER_GREAT_ERROR 1005
#define CONNECT_ERROR 1006
#define RECV_ERROR 1007