C# sockaddr to sockaddr_in

2019-09-16 14:35发布

问题:

I am writing an application in C# that hooks the connect function call of another program and reads the IP it is connecting to. (I know it is IPv4)

Currently it hooks, intercepts and forwards the function call and I get the variables but since connect in winsock is called with a sockaddr* variable as the second argument, I need cast this to a sockaddr_in to get the IP address. (Unless there is a way to retrieve the ip out of the sa_data field, which I couldn't find information about.)

This is where I am stuck. I generated the C# code for the structs using the InteropSignatureToolkit (generated code: http://pastebin.com/twvGw030), but I don't really see how to cast the sockaddr struct to sockaddr_in. In C++ this would be quite easy, but I don't know how to do it in C#.

Thanks for taking your time to read this and I hope you can help me. :)

回答1:

Use an IntPtr in the p/invoke declaration, then you can use Marshal.PtrToStructure. First use sockaddr to find out sa_family, then call Marshal.PtrToStructure again with the more specific type.