其他PC无法通过C连接到我的服务器

时间:2014-09-29 16:47:40

标签: c connection bind

我在端口100上用C创建了一个服务器。问题是,如果我的电脑上有人写了 telnet myip 100 ,他就无法连接到我的服务器了!

代码:

#include <io.h>
#include <stdio.h>
#include <winsock2.h>
#include <Ws2tcpip.h>
#include "ws2tcpip.h"
#pragma comment(lib,"ws2_32.lib")

int main(int argc , char *argv[])
{
    WSADATA wsa;
    SOCKET s, new_socket;
    struct sockaddr_in server, client;
    int c;
    char *message;

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

    printf("Winsock 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_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(100);
    int inet_pton(int af, const char *src, void *dst);

    //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;
}

我的提供者是Fastweb(我来自意大利,我不知道你是否知道它)。 有什么问题?服务器或提供商的源代码?

非常感谢你!

0 个答案:

没有答案