gpt4 book ai didi

c - 使用c进行套接字编程时连接到远程服务器时出错

转载 作者:行者123 更新时间:2023-11-30 19:11:10 25 4
gpt4 key购买 nike

这是一个示例代码,我尝试将请求传递到服务器并获取所需的数据。但是我连接到远程服务器的代码没有像我想象的那样工作。

if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}

puts("Connected");

我不知道为什么条件值低于零。为什么连接没有完成?

完整代码:

    /*
Create a TCP socket
*/

#include<stdio.h>
#include<winsock2.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char *message , server_reply[2000];
int recv_size;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");


server.sin_addr.s_addr = inet_addr("74.125.235.20");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );

//Connect to remote server
if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}

puts("Connected");

//Send some data
message = "GET / HTTP/1.1\r\n\r\n";
if( send(s , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR)
{
puts("recv failed");
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
server_reply[recv_size] = '\0';
puts(server_reply);
closesocket(s);
WSACleanup();

return 0;
}

最佳答案

在分配之前,您需要将整个 sockaddr_in 初始化为零。

memset( &server, 0, sizeof(server) );
server.sin_addr.s_addr = inet_addr("74.125.235.20");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );

我复制了你的代码并尝试了一下,它似乎有效,也许你有防火墙干扰。

顺便说一句,我将您的 inet_addr 调用更改为

InetPtonA( AF_INET, "74.125.235.20", &server.sin_addr.s_addr );

关于c - 使用c进行套接字编程时连接到远程服务器时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40603442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com