我正在使用WinSock
并且我有一个问题:如果我定义MY_IP
为“127.0.0.1”,这是可行的,但我不想将其定义MY_IP
为“109.95.202.122”,但它不起作用。
我失败了:Fail bind()
和Listen Error
#pragma comment(lib, "Ws2_32.lib")
#include <sdkddkver.h>
#include <conio.h>
#include <stdio.h>
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <string>
#include <process.h>
#define MY_IP "109.95.202.122"
using namespace std;
int main()
{
WSADATA wsaData;
int result = WSAStartup( MAKEWORD( 2, 2 ), & wsaData );
if( result != NO_ERROR )
cout << "Initialization error." << endl;
SOCKET mainSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if( mainSocket == INVALID_SOCKET )
{
printf( "Error creating socket: %ld\n", WSAGetLastError() );
WSACleanup();
return 1;
}
sockaddr_in service;
memset( & service, 0, sizeof( service ) );
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(MY_IP);
service.sin_port = htons( 27015 );
if(bind(mainSocket, (SOCKADDR*)&service, sizeof(service))== SOCKET_ERROR)
{
cout << "Fail bind()" << endl;
closesocket( mainSocket );
}
if(listen(mainSocket, 1) == SOCKET_ERROR)
{
cout << "Listen Error";
}
cout << "Oczekiwanie na polaczenie" << endl;
SOCKET acceptSocket = SOCKET_ERROR;
while( acceptSocket == SOCKET_ERROR )
{
acceptSocket = accept( mainSocket, NULL, NULL);
}
if( acceptSocket != SOCKET_ERROR)
{
cout << "Connected ! :D" << endl;
for(;;)
{
char chWiadomosc[1000];
recv(mainSocket, chWiadomosc, sizeof(chWiadomosc), NULL);
}
}
}