1. 程式人生 > >防火牆對於127.0.0.1地址的不進行攔截

防火牆對於127.0.0.1地址的不進行攔截

使用迴環地址進行本地TCP/IP通訊,防火牆不會進行攔截。

#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"wsock32.lib")

void main()
{
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0)
        return;

    if (LOBYTE(wsaData.wVersion) != 2 ||
        HIBYTE(wsaData.wVersion) != 2)
    {
        WSACleanup();
        return;
    }
    SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0);
    SOCKADDR_IN sockaddr;
    sockaddr.sin_addr.S_un.S_addr = htonl(INADDR_LOOPBACK);
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(8006);
    bind(sockSrv, (SOCKADDR*)&sockaddr, sizeof(SOCKADDR));
    listen(sockSrv, 5);
    SOCKADDR_IN addrClient;
    int len = sizeof(SOCKADDR);
    while(1)
    {
        SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &len);
        char SendBuf[100];
        send(sockConn, SendBuf, sprintf(SendBuf,"server") + 1, 0);
        char recvBuf[100];
        recv(sockConn, recvBuf, 100, 0);
        printf("%s\n", recvBuf);
        closesocket(sockConn);
    }
}


#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"wsock32.lib")

void main()
{
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0)
        return;

    if (LOBYTE(wsaData.wVersion) != 2 ||
        HIBYTE(wsaData.wVersion) != 2)
    {
        WSACleanup();
        return;
    }
    SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);
    SOCKADDR_IN sockaddr;
    sockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//INADDR_LOOPBACK;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(8006);
    connect(sockClient, (SOCKADDR*)&sockaddr, sizeof(SOCKADDR));
    char recvBuf[100] = {0}, sendBuf[100] = {0};
    recv(sockClient, recvBuf, 100, 0);
    printf("%s\n", recvBuf);
    send(sockClient, sendBuf, sprintf(sendBuf, "client") + 1, 0);
    closesocket(sockClient);
    WSACleanup();
}