所以我想在我的电脑上运行一个实时服务器来连接并从别人那里获取信息。我以为我可以让其他人连接到我未使用的端口上的IP地址。因此,例如,如果我的假设IP地址是214.231.34.12和端口50000并且我打开te连接并将此信息提供给某人,他们可以连接到它并通过TCP向我发送信息。
我以为我可以使用这段代码:
// TCPClient.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
/*
Live Server on port 50000
*/
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s, new_socket;
struct sockaddr_in server, client;
int c;
char *message;
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");
//Prepare the sockaddr_in structure
server.sin_addr.s_addr = inet_addr("214.231.34.12");
server.sin_family = AF_INET;
server.sin_port = htons(50000);
//Bind
if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//Listen to incoming connections
listen(s, 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while ((new_socket = accept(s, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
{
puts("Connection accepted");
//Reply to the client
message = "Hello Client , I have received your connection. But I have to go now, bye\n";
send(new_socket, message, strlen(message), 0);
}
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d", WSAGetLastError());
return 1;
}
closesocket(s);
WSACleanup();
return 0;
}
但它没有绑定连接。整个TCP和winsocket的东西对我来说都是全新的,我不明白我应该如何区别对待。我知道这段代码还没有收到任何信息,这只是我目前尝试工作的连接。这不是正确的设置方法吗?
bind()因Windows套接字错误10049
而失败答案 0 :(得分:1)
通过互联网建立TCP连接存在很多障碍:
是一个完整的新世界链接到互联网上的个人电脑,概念是一样的,但实现它......
答案 1 :(得分:0)
所以它可能是一个答案,但也许我必须使用另一个端口作为datenwolf建议。
我发现无法绑定到我的ISP的ipaddress。所以我转发了我想要使用的端口,然后连接到我的电脑的ipaddress,如下所述:
connecting to an IP address instead of localhost?
我试过了,所以我将代码中的ipaddress更改为:
//Prepare the sockaddr_in structure
server.sin_addr.s_addr = inet_addr("192.168.178.93");
server.sin_family = AF_INET;
server.sin_port = htons(50000);
然后当我用telnet连接到214.231.34.12和端口50000时,连接正常工作!我只是想知道这是否是一个有效的结果?