为什么我的socket套接字老是创建失败?

crazysun 2003-08-07 04:51:01
以下是我的源程序,一个简单的服务器端程序,
可最后结果老是显示“socket error!”
请各位大虾帮忙解答!

#include <winsock.h>
#include <stdio.h>
#define USERPORT 12000

void main(void)
{
int sock;
struct sockaddr_in server, client;
int msgsock;
char buf[1024];
int rval, len;

/* 建立套接字 */
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET)
{
printf("socket error!\n");
exit(1);
}

server.sin_family = AF_INET;
server.sin_port = htons(USERPORT);
server.sin_addr.s_addr = INADDR_ANY;
if (bind(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("bind error!\n");
exit(1);
}

/* 开始接收连接 */
listen(sock, 5);
len = sizeof(struct sockaddr);
do
{
msgsock = accept(sock, (struct sockaddr *)&client, (int *)&len);
if (msgsock == -1)
printf("accept error!\n");
else do
{
memset(buf, 0, sizeof(buf));
if ((rval = recv(msgsock, buf, 1024, 0)) < 0)
printf("receive error!\n");
if (rval == 0)
printf("ending connection \n");
else
printf("%s\n", buf);
}while (rval != 0);
closesocket(msgsock);
} while (1);

exit(0);
}
...全文
174 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
fantiyu 2003-08-08
  • 打赏
  • 举报
回复
没初始化WSA
feeboby 2003-08-07
  • 打赏
  • 举报
回复
就是这个函数放在最前面WSAStartup
wkgenius 2003-08-07
  • 打赏
  • 举报
回复
改成下面这样:

#include <winsock.h>
#include <stdio.h>
#define USERPORT 12000

void main(void)
{
int sock;
struct sockaddr_in server, client;
int msgsock;
char buf[1024];
int rval, len;

WSADATA wsd;
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
printf("wsastartup error!\n");
exit(1);
}

/* ½¨Á¢Ì×½Ó×Ö */
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET)
{
printf("socket error!\n");
exit(1);
}

server.sin_family = AF_INET;
server.sin_port = htons(USERPORT);
server.sin_addr.s_addr = INADDR_ANY;
if (bind(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("bind error!\n");
exit(1);
}

/* ¿ªÊ¼½ÓÊÕÁ¬½Ó */
listen(sock, 5);
len = sizeof(struct sockaddr);
do
{
msgsock = accept(sock, (struct sockaddr *)&client, (int *)&len);
if (msgsock == -1)
printf("accept error!\n");
else do
{
memset(buf, 0, sizeof(buf));
if ((rval = recv(msgsock, buf, 1024, 0)) < 0)
printf("receive error!\n");
if (rval == 0)
printf("ending connection \n");
else
printf("%s\n", buf);
}while (rval != 0);
closesocket(msgsock);
} while (1);

exit(0);
}

问题就是你没有进行WSA初始化。

18,356

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧