C# Finding a socket ID? - c#

Recently I have started working on a program that will monitor the packets of one of my open-source programs in an attempt to learn more about programming and networking. Also, I want to add additional functionality to the program without editing the source, like an external control panel.
(I used WPE Pro to filter packets in case you'r wondering, WireShark is too much hassle for such a simple task.) One thing bothers me though, the Socket ID.
I know what it is, and I've asked a question about it before, but I cant figure out how to use it/assign one/intercept one.
Without the right socket ID, my program wont be able to do anything, so my question is if it's possible to find out what Socket ID a socket is using, once you capture the packet?
If not, are there any other ways of doing? -or possible other languages like Visual Basic?
Thank you for your time.

If, by socket ID, you mean the return value of a successful call to socket() function, I don't think there's a way.
The closest thing you can obtain is the process ID because, as you may already know, each IP packet has a destination that's described by the tuple (IP address, port) and inside a system only one socket can be successfully bound to that tuple. Utilities like TCPView are able to map an IP tuple to a process, so a way does exist if that information is enough for you.
If that's not the case, I'm not aware of any method to retrieve the socket ID you need if the target application is not collaborative.

This library: SharpPcap promises doing capturing, injecting, analyzing and building packets using any .NET language such as C# and VB.NET (more info).
It is the library used by Wireshark and it is for sure that it can capture and analyze.

socket() returns a file descriptor if this is what you are referring to as a socket ID then the ways to get this without the process's collaboration on windows are limited. FWIW on linux open FDs are enumerated in the proc filesystem.
That being said, the only thing you would be able to do with the fd is send additional information from the socket. You could also read from the fd, but any data read in this way would not be sent to the application that owns the socket. Without some coordination, that would probably not be what you desire as you would just get bits and pieces of data.
If just want to be able to listen in on the traffic in your program, then something like packet filtering should be sufficient so I assume you actually want to be able to be like a man in the middle for it.
If this is the case, then the best thing to do would actually be to set your application up as a proxy for your other service.
By this I mean, write a program that opens a listening port and accepts connections when a connection is initiated, it should immediately open its own connection to a pre-configured IP:port combination and begin forwarding traffic. Once this is written it's a simple matter to inspect the traffic before forwarding and possibly modify it.
If your program is a server, run it on a non-standard port, configure this application to open the server's normal port and then forward connections to the non-standard port you set up on localhost.
If your program is a client, simply point the interceptor application at the server and choose a random listen port on your box. Then configure the client to connect to this listen port as though it were the server.
This should work for pretty much anything. The only caveat is if the traffic is encrypted you will (obviously) not be able to inspect/modify it. This is effectively the same as placing your application behind a NAT.

Related

What ip/port should i use for TCP Socket Server/Client connection?

i made basic TCP Socket server and client console application in c# with listener etc.. it works well with both server and client executed in same machine(127.0.0.1:10048). I want to try it with different machines in same network(both connected to same modem).
Which ip port should i use? I need help.
Thanks
You should use a port in the ephemeral port range. The ephemeral port range is the range of port numbers that is being selected from if you active connect to a server. The point is that it is free for use. Your kernel will skip the port numbers that are already in use so you don't have to worry about that either.
http://en.wikipedia.org/wiki/Ephemeral_port
And on top of this it is best not to hardcode your port numbers and ip adresses where you bind to connect or send to.
Make sure your OS firewall is turned off. For instance windows firewall can block this type of traffic.
Do not use just any free port that you detect is not in use. For instance you may not have an FTP or Telnet server running on your system, but that does not mean that you can just hijack those ports. From a functional point of view it will work if you do, but then you cannot run those services anymore somewhere in the future where you might need them, or your application will start failing. Which fails depends on which application is first started and starts using the port first.
When you bind an ip# you should use INADDR_ANY. Loopback communication will still work if you use this, you probably already did, most examples include it. Sending or connecting to an IP# should come from a configuration file (data driven) or commandline parameters. The IP# depends of course on the machine you want to communicate with.
Open your CMD and type ipconfig. There you can see your IPv4 address, that you should use to connect. The port doesn't really matter. Make sure to turn of your firewall(s) to allow a connection

How to send SYN packet using C# or Java

I want to send SYN packet to a remote host, now the problem is that if I use any of the classes of .NET framework then I cannot to do this; e.g. TCP Client takes Host ip and port number and establishes connection, same is the case with ClientSocket class in java.
I want to control the connection establishment my self; I mean I want to send the connection request (SYN packet) then wait for the connection reply and then send the packet. I know that it might not be easy without external libraries, so if any one can guide me how to do it in either C# or Java. .
Rather than commenting to both answers so far ... raw sockets have been restricted in Windows since XP (countermeasure to malware attacks). Read the following:
http://msdn.microsoft.com/en-us/library/ms740548(v=vs.85).aspx
Once that's done you can certainly build a raw socket following their rules based on Mat's answer for Java or Ritch's for C#.
It will be heavily restricted access, and very system dependent either way. I'm unaware of a method to complete the 3 way handshake and transmit data across TCP/UDP (though I'd be interested in hearing one).
I thought I should make one quick amendment to this answer. If you don't use winsock and instead use a different TCP stack, you can probably get what you want (but this is still not directly availalbe within the OS). Look at this as an example offering: http://www.komodia.com/tcpip-library-v5-1/ or this previous SO thread What is a popular, multi-platform, free and open source socket library
What you're looking for is called raw sockets. I don't know about C#, but there are libraries in Java that let you do that, e.g. RockSaw. You cannot do it using pure Java as far as I know.
Be warned that on some operating systems (Linux at least), you need administrator privileges to be able to open raw sockets. And there are a bunch of restrictions on Windows. (See that page I linked.)
Use the Socket class with a SocketType of raw, and the correct protocol type. I think you want TCP.
var sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Tcp);

Forward UDP packets to several IPs maintaining the original source address

I have a working system that receives data via UDP packets sent to a fixed IP:Port and I want to use a program (some kind of proxy?) to send a copy of those packets to a new IP:Port (or a list of IP:Ports, but all inside the same LAN as the program).
Not as easy as it seems, because I need the copied packets to have the same Source IP address as the original ones.
In my research, I have found PCap.Net (WinPCap .NET wrapper) to be useful, because it can build a Packet from scratch and it supports modifying all the address fields. I have managed to capture the packets and build them. But somewhat they are not arriving at the desired destination (!?). Should I use a different PacketCommunicator to receive and send them?
Anyway, the question is not fully related to PCap.Net but to know alternative ways to achieve my desired goal. Via a free application? commercial application? Open source sample? Any other library to use?
My systems are Windows based (no Linux available here). And I have C# (.NET) experience (I can not use a C++ library, if NET bindings are not available).
Many thanks for your help
I know it's an old question, but this is the answer:
http://code.google.com/p/samplicator/
Listens for UDP and forwards it to one or more other IP addresses, optionally spoofing (the original) source IP address.
Used for forwarding netflow/sflow/syslog etc. packets.
you should think about network first. it may not be possible if traffic needs to go through router.
the original packet came through:
source->router->your server
if you are trying to sent it back out like so:
your server->router->another computer
then the router may not even accept this traffic, since it can not originate from your computer, according to routers configuration. just think about it - i could send traffic as anybody, if that was allowed.
however, in LAN that's very doable (unless you have some sort of MAC spoofing protection on your switches)
What you are trying to do is called "UDP Forwarding". You receive a UDP packet and then forward it to another host
Here is an application that does that (seems to be free)
in addition to keeping the source ip address and changing the destination ip address
you MUST swap the source and destination mac addresses.
if you send a raw packet out to your router/switch/modem, but the mac address is not addresses to it.
it will be dropped.
basicly, you have to revise every network layer your dealing with, and handle addressing approperately.
Sorry for my spelling
If you try to spoof the destination address to do things like netflow relaying you often will get blocked by anti-spoofing routers inbetween. I encountered this with AWS for example.
The solution is to take the RAW udp packet and then just send that along to your new destination inside another udp packet. When it reaches the destination you have to "unwrap" the packet and then send it to itself on the loopback interface (essentially "unwrapping").
You can do this with python code with the sockets module.

How do I Control a Device’s Embedded Control Software in C# using HTTP?

I have a piece of hardware with an embedded user control accessed by typing the device's IP Address into a web browser. The device is connected directly to my PC via x-over ethernet cable and static IP's. I need to integrate the control of the device into my C# application.
My thought was to use a packet sniffer to monitor the traffic between my PC and the device while at the same time playing with the device's controls in my web browser. Then finding out which packets that my PC is sending correspond with which controls I am using at that time. Then I can create a class of HTTP or TCP packets in my C# application and send them to the device using the Socket class.
However, I dont have much expereince with network protocols, so when I am using Wireshark to monitor the traffic between my PC and the device, I am not sure where to even start when finding out which packets do what. Does anyone have any ideas? I am open to anything. Thanks!!
EDIT:
Its hard to explain exactly what my device is, but its basically an elaborate sensor and typically used in industrial applications, so it could likely be using Modbus, which I am moderately familiar with. Do you know how I can tell which protocol is being used by examining the packets? I noticed (using Wireshark) that the packets being sent from my PC to the device occur in a pattern of 1 HTTP packet, then 5 TCP packets and repeat that same sequence as long as the control is open in my browser. Are there any resources that might give me a better understanding of what is going on?
If this is browser controlled, my first thought would be to examine the web pages the device sends to your browser and see what the browser is instructed to do when you manipulate the controls - this seems much easier than messing around with Wireshark.
Is there something I'm missing that makes this impossible (such as a Flash-based control system)? If it's just done with HTML or Javascript, and HTML POST messages or something a bit more sophisticated like Ajax, it should be relatively easy to work out the interface.
Depending on the device it will either be using a variant of the modbus protocol (http://en.wikipedia.org/wiki/Modbus) or something obscure and propriatory.
The best thing to do is to keep sending the same command to the device over and over again until you can recognise similarities in the packets.
If it is propriatory it will probably be something simple like a command/data pair or possibly an XML blob. If you're really unlucky it will be compressed or encoded but unless you're hacking a game or a cash machine this is unlikely.
Asking the manufacturer of the device if they can give you the spec often works as well.

Discover computers on local network with specific open port using .NET

I need to "discover" local computers running my windows WCF service, so I can talk to them. Right now you have to enter manually the ipaddress:port combination, but I would like to have a (web?) application that monitors the machines running the service and reports on it.
When I try to connect to an invalid ip/port it takes "forever" to timeout, so it's not feasible to check all the ip on my local network. Is there a quick way to discover which machines have the port open (all of them have the hole in the firewall for that specific port)
TIA
I have done this several time. Just set the timeout value very low.
ALso if its a real machine but without the port open it should fail fast anyway. If you are doing a subnet sweep then, yes, you need to have a (say) 1 second timeout.
Multi-thread the sweep - this is a fun thing to code
edit: I cant find my code. here is link to solution from somebody else
http://social.msdn.microsoft.com/forums/en-US/netfxnetcom/thread/c8161442-61b5-4840-999b-5bb36bda0b6d/
could you have the client configured to contact the web app and report with it's location that it is running your wcf service?
that would require the web app to be running on a known machine that doesnt change.
Why not make them use multicast to broadcast a "HELLO" packet every so often. This is assuming of course that multicast is available in your scenario and your not talking across routing domains. Simply use the "HELLO" packet contents such as ipv4 unicast address to ensure you know what you should be talking to. Of course you don't need to use multicast, you can just send a broadcast to 255.255.255.255 which is not a complex task and then listen for these messages. The benefit of this is that you could also enable negotiation of the port. For instance, if your application generally binds to a port but this port is unavailable, it can automatically choose a port and let you know what port it is bound to. Avoids manual configuration maintenance and headaches involved. Hell, it can even use broadcast to send a message and check if it received it. If it doesn't, fire off an alert letting the systems administrator know.
I use something along these lines for managing test harnesses for soft switches (voice) and it works very well.
Of course, I could be very much off on this. Just thinking out off the box here.

Categories