C# sockaddr to sockaddr_in

荒凉一梦 提交于 2019-12-25 03:14:13

问题


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.



来源:https://stackoverflow.com/questions/11732189/c-sharp-sockaddr-to-sockaddr-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!