socket为什么连接失败?请看代码

filter023 2003-04-14 11:10:05
//程序是一个客户端
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <conio.h>
#include <iostream>

using namespace std;
string Str;
//*********************

void SendMsg()
{
char ch;
ch = getchar();
if (ch == '\n')
{
cout<<"RT!"<<endl;
Str = "RT!";
}
while (ch != '\n')
{
Str = Str + ch;
ch = getchar();
}
}
int main(int argc,char** argv)
{
WSADATA wsaData;
SOCKET sClient;
static char* szBuffer;
int ret;
struct sockaddr_in Server;
struct hostent *host = NULL;
string IP;
char ch;
bool bSendOnly = false;

int SocketErrorCode = 0;
szBuffer = new char(0);
if (WSAStartup(MAKEWORD(2,0),&wsaData) != 0)
{
SocketErrorCode=1;
cout<<"Create Socket Error!"<<endl;
return 1;
}
sClient = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (sClient == INVALID_SOCKET)
{
cout<<"Create Socket Error!"<<endl;
}
cout<<"Please Input Host IP:"<<endl;
cin>>IP;
Server.sin_family = AF_INET;
Server.sin_port = 5150; //此处以前写成的
Server.sin_addr.s_addr = inet_addr(IP.c_str());
if (connect(sClient,(struct sockaddr*)&Server,sizeof(Server)) == SOCKET_ERROR)
{
cout<<"Connect Server Failed!"<<endl;
//进来了,到此出错 为什么?
}

////以下省略***
...全文
74 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
filter023 2003-04-14
  • 打赏
  • 举报
回复
知道了 其实以前是用 htons()的 突然不能用了 所以去掉了 刚才改回去 居然又好了
alphapaopao 2003-04-14
  • 打赏
  • 举报
回复
Server.sin_port = 5150;
很有可能你是错在这里,网络上的整数和你机器上的整数是不一样的,你需要使用下面函数进行转换

hton()

这个函数有不同的版本,分别用于不同长度的整数。

============================================================================
http://www.betajin.com/alphasun/index.htm 给我发信息请附带原帖地址
http://alphasun.18en.com/ http://shakingtoolkit.9126.com/
DocWizard C++程序文档自动生成工具 | Wave OpenGL | HttpProxy | AjaxParser词法分析
maoxianwang 2003-04-14
  • 打赏
  • 举报
回复
关注,蹭分

18,356

社区成员

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

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