- 论坛徽章:
- 0
|
简单的socket程序问题
#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>;
#define SERVERPORT 3333 /*服务监听端口号*/
#define BACKLOG 10 /*最大连接数*/
int main(void)
{
int socketfd, client_fd;
int sin_size;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
int ret;
/* 已修改*/
socketfd = socket(AF_INET,SOCK_STREAM,0); /*创建socket*/
if (socketfd < 0)
{
perror("socket创建出错" ;
exit(0);
}
/* t添加初始化 */
memset(&my_addr, 0, sizeof(struct sockaddr_in));
my_addr.sin_family = AF_INET;
/* port is unsigned short data type */
/*my_addr.sin_port = htonl(SERVERPORT);*/
my_addr.sin_port = htons(SERVERPORT);
my_addr.sin_addr.s_addr=INADDR_ANY;
/*bzero(&(my_addr.sin_zero), ; */
/*if(bind(socketfd,(struct socketaddr *) &my_addr,sizeof(struct sockaddr))==-1)*/
ret = bind(socketfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
if (ret < 0)
{
perror("bind 出错" ;
exit(1);
}
ret = listen(socketfd,BACKLOG);
if (ret < 0)
{
perror("listen出错" ;
exit(1);
}
while(1)
{
sin_size = sizeof(struct sockaddr_in);
/* 填加初始化 */
memset(&remote_addr, 0, sin_size);
/* 已修改 */
//if ((client_fd = accept(socketfd,(struct socketaddr *)&remote_addr,&sin_size))==-1)
client_fd = accept(socketfd,(struct sockaddr *)&remote_addr, &sin_size);
if (client_fd < 0)
{
perror("accept出错" ;
continue;
}
printf("received a connect from %s\n",inet_ntoa(remote_addr.sin_addr));
if (!fork())
{
if (send(client_fd,"Hello,you are connected!\n",26,0)==-1)
perror("send出错" ;
exit(0);
}
close(client_fd);
}
}
/* 错误太多了,注意编程风格,变量应注意初始化 */ |
|