go中引用socket库 ws2_32

本文介绍了一个使用Go语言实现的功能,该功能能够监听本地进程的启动,并将相关信息通过UDP协议发送到指定端口。代码示例展示了如何利用Windows API进行进程监听,以及如何通过Go调用C语言代码来实现这一目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#cgo windows,amd64 LDFLAGS: -lWS2_32



引用的C头部添加上面这个  写个例子


package main
/*
#cgo windows,amd64 LDFLAGS:  -lWS2_32
#include <windows.h>
#include <stdio.h>
#include "define.h"
#include <windows.h>
#define host "127.0.0.1"
#define port 5556
#pragma comment(lib, "ws2_32.lib")
void socket_def(SOCKET *sock, char *host_t, int port_t)
{
    WSADATA wsaData;
    struct sockaddr_in saddr;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        printf("error");
    }
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(port_t);
    saddr.sin_addr.s_addr = inet_addr(host_t);
    *sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (*sock == INVALID_SOCKET)
    {
        printf("socket initialize failed: %d/n", WSAGetLastError());
    }

}

int  get_process_info()
{
    HANDLE        hDevice;
    int        status;
    HANDLE        m_hCommEvent;
    ULONG        dwReturn;
    char        outbuf[255];
    CHECKLIST    CheckList;

    SOCKET sock;
   WSADATA wsaData;
    struct sockaddr_in saddr;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        printf("error");
    }
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(port_t);
    saddr.sin_addr.s_addr = inet_addr(host_t);
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    hDevice = NULL;
    m_hCommEvent = NULL;
    hDevice = CreateFile("\\\\.\\MyEvent",
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    if (hDevice == INVALID_HANDLE_VALUE)
    {
        printf("createfile wrong\n");
        getchar();
        return 0;
    }

    m_hCommEvent = CreateEvent(NULL,
        0,
        0,
        NULL);
    printf("hEvent:%08x\n", m_hCommEvent);

    status = DeviceIoControl(hDevice,
        IOCTL_PASSEVENT,
        &m_hCommEvent,
        sizeof(m_hCommEvent),
        NULL,
        0,
        &dwReturn,
        NULL);
    if (!status)
    {
        printf("IO wrong+%d\n", GetLastError());
        getchar();
        return 0;
    }

    CheckList.ONLYSHOWREMOTETHREAD = TRUE;
    CheckList.SHOWTHREAD = TRUE;
    CheckList.SHOWTERMINATETHREAD = FALSE;
    CheckList.SHOWTERMINATEPROCESS = FALSE;
    status = DeviceIoControl(hDevice,
        IOCTL_PASSEVSTRUCT,
        &CheckList,
        sizeof(CheckList),
        NULL,
        0,
        &dwReturn,
        NULL);
    if (!status)
    {
        printf("IO wrong+%d\n", GetLastError());
        getchar();
        return 0;
    }

    printf("      [Process Name]    [PID]    [TID]    [Parent Process Name]    [PID]    [TID]\n");
    while (1)
    {
        ResetEvent(m_hCommEvent);
        WaitForSingleObject(m_hCommEvent, INFINITE);
        status = DeviceIoControl(hDevice,
            IOCTL_PASSBUF,
            NULL,
            0,
            &outbuf,
            sizeof(outbuf),
            &dwReturn,
            NULL);
        if (!status)
        {
            printf("IO wrong+%d\n", GetLastError());
            getchar();
            return 0;
        }
        printf("%s", outbuf);
        sendto(sock,outbuf,strlen(outbuf),0,(struct sockaddr *)&saddr,sizeof(saddr));


    }

    status = DeviceIoControl(hDevice,
        IOCTL_UNPASSEVENT,
        NULL,
        0,
        NULL,
        0,
        &dwReturn,
        NULL);
    if (!status)
    {
        printf("UNPASSEVENT wrong+%d\n", GetLastError());
        getchar();
        return 0;
    }

    status = CloseHandle(hDevice);
    status = CloseHandle(m_hCommEvent);
    getchar();
    return 0;
}
*/
import "C"
import (
	"net"
	"fmt"
)
func main() {

	C.get_process_info()

	var localaddress,_=net.ResolveUDPAddr("udp",":5556")
	var udplistener,err=net.ListenUDP("udp",localaddress)
	if err!=nil{
		fmt.Print("error")
		return
	}
	defer  func(){

		udplistener.Close()
	}()

     var buf[255]byte
	n,_,err:=udplistener.ReadFromUDP(buf[0:])
	if err!=nil{
		fmt.Print("dd")
		return
	}
	fmt.Print(string(buf[0:n]))
}

监听到进程启动通过socket发送给指定的端口。

========================================================================================================== test session starts =========================================================================================================== platform win32 -- Python 3.7.3, pytest-7.4.4, pluggy-1.2.0 -- d:\python\python.exe cachedir: .pytest_cache metadata: {'Python': '3.7.3', 'Platform': 'Windows-10-10.0.22621-SP0', 'Packages': {'pytest': '7.4.4', 'pluggy': '1.2.0'}, 'Plugins': {'html': '3.2.0', 'metadata': '3.0.0', 'ordering': '0.6', 'rerunfailures': '13.0'}} rootdir: D:\pythonProject\ryTest configfile: pytest.ini testpaths: ./scripts plugins: html-3.2.0, metadata-3.0.0, ordering-0.6, rerunfailures-13.0 collected 2 items scripts/test_01.py::Test01::test_login DevTools listening on ws://127.0.0.1:61065/devtools/browser/19c757d3-cfd7-4475-9a59-c604539f9b1c [15068:2140:0620/153723.761:ERROR:net\socket\ssl_client_socket_impl.cc:892] handshake failed; returned -1, SSL error code 1, net_error -101 [15068:2140:0620/153723.856:ERROR:net\socket\ssl_client_socket_impl.cc:892] handshake failed; returned -1, SSL error code 1, net_error -101 PASSED scripts/test_01.py::Test01::test_home FAILED ================================================================================================================ FAILURES ================================================================================================================ ____________________________________________________________________________________________________________ Test01.test_home ____________________________________________________________________________________________________________ self = <scripts.test_01.Test01 object at 0x00000249B20B90B8> def test_home(self): self.Homeproxy.go_page() > self.AddProxy.go_add("买菜","50") scripts\test_01.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ page\mp\add_page.py:48: in go_add self.AddHandle.input_addname(addname) page\mp\add_page.py:35: in input_addname UtilsDriver.get_mp_driver().switch_to.frame(self.AddPage.find_iframe2()) page\mp\add_page.py:20: in find_iframe2 return self.get_element(self.iframe2) base\mp\base.py:11: in get_element element=wait.until(lambda x:x.find_element(*location)) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <selenium.webdriver.support.wait.WebDriverWait (session="70fff24adb85ae9b274759a5b8bcdb58")>, method = <function BasePage.get_element.<locals>.<lambda> at 0x00000249B20B51E0>, message = '' def until(self, method, message: str = ""): """Calls the method provided with the driver as an argument until the \ return value does not evaluate to ``False``. :param method: callable(WebDriver) :param message: optional message for :exc:`TimeoutException` :returns: the result of the last call to `method` :raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs """ screen = None stacktrace = None end_time = time.monotonic() + self._timeout while True: try: value = method(self._driver) if value: return value except self._ignored_exceptions as exc: screen = getattr(exc, "screen", None) stacktrace = getattr(exc, "stacktrace", None) time.sleep(self._poll) if time.monotonic() > end_time: break > raise TimeoutException(message, screen, stacktrace) E selenium.common.exceptions.TimeoutException: Message: E Stacktrace: E GetHandleVerifier [0x0x7ff704133905+25605] E (No symbol) [0x0x7ff704083a10] E Microsoft::Applications::Events::EventProperty::to_string [0x0x7ff7043b6f1a+1962506] E (No symbol) [0x0x7ff703e986c4] E (No symbol) [0x0x7ff703e9898b] E (No symbol) [0x0x7ff703ed9af7] E (No symbol) [0x0x7ff703eb9e8f] E (No symbol) [0x0x7ff703e8ea5d] E (No symbol) [0x0x7ff703ed75df] E (No symbol) [0x0x7ff703eb9bb3] E (No symbol) [0x0x7ff703e8df56] E (No symbol) [0x0x7ff703e8d463] E (No symbol) [0x0x7ff703e8dd83] E (No symbol) [0x0x7ff703f8e10d] E (No symbol) [0x0x7ff703f9dce8] E Microsoft::Applications::Events::EventProperty::to_string [0x0x7ff7042188d9+265161] E Microsoft::Applications::Events::EventProperty::to_string [0x0x7ff7042201b1+296097] E (No symbol) [0x0x7ff7040921b1] E (No symbol) [0x0x7ff70408a654] E (No symbol) [0x0x7ff70408a7a3] E (No symbol) [0x0x7ff70407b976] E BaseThreadInitThunk [0x0x7ffb94f0259d+29] E RtlUserThreadStart [0x0x7ffb9580af78+40] C:\Users\YangYuQuan\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\support\wait.py:95: TimeoutException ======================================================================================================== short test summary info ========================================================================================================= FAILED scripts/test_01.py::Test01::test_home - selenium.common.exceptions.TimeoutException: Message: ====================================================================================================== 1 failed, 1 passed in 17.78s ======================================================================================================
最新发布
06-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值