Connecting peers in Lidgren from a server - c#

I would like to set up a P2P matchmaking server. The situation is as follows:
I have 2+ peers behind NAT'd router(s).
I have a server behind a port-forwarded router on a static IP.
The server's job is to register the contact information of each peer, and send it any other peer when requested.
A peer could then query the server for a list of others, and directly connect to them.
Presently, peers can connect to the server, register their addresses, and query it for other peers' addresses. My issue is introducing the peers to each other.
I am presently getting the internal and external IP addresses of each peer like so. It is heavily based around the Master Server Sample that ships with Lidgren; however, that merely connects users to client/server sessions, while I require peer to peer.
//client code; getting our internal IP and sending it to the server
NetOutgoingMessage om = server_client.CreateMessage(); //create message on the server's connection
... //header
IPAddress mask;
var endpoint = new IPEndPoint(NetUtility.GetMyAddress(out mask), peer_client.Port); //gets the internal IP address
... //write message data and send to server
When the server gets a request, or when a peer is registered to the server, it gets that peer's external IP from the connection message. We then have access to both IPs from both peers when handling a request:
//server code, handling the peer request message:
...
string key = msg.ReadString();
Output("Requesting peer: " + key);
IPEndPoint requester_internal = msg.ReadIPEndPoint();
IPEndPoint requester_external = msg.SenderEndPoint;
//attempt to find requested user
User u = null;
if (Users.TryGetValue(id, out u))
{
IPEndPoint target_internal = u.IPInternal;
IPEndPoint target_external = u.IPExternal;
...
//send the requested IPs to the sender, and the sender's IPs to the target.
}
Now, the issue is how to connect the peers to each other using this information (or, whatever other information is required to make the connection), since the other infrastructure is already functional.
My first attempt was using the built-in Introduce method:
//server code, continuing from the above
//instead of directly sending IPs to users, introduce them ourselves
s_server.Introduce(target_internal, target_external, requester_internal, requester_external, key);
This seemed to work to some degree, but it connected to the server connection on each client instead of the peer connection, and only succeeded on the sender.
Attempting to manually connect with the sent IPs resulted in endless "attempting to connect" messages:
//peer code; handling 'other peer data received' msg
IPEndPoint peer_internal = msg.ReadIPEndPoint();
IPEndPoint peer_external = msg.ReadIPEndPoint();
Output("SERVER: Recieved peer IP. Attempting to connect to:\n" + peer_internal.ToString() + "\n" + peer_external.ToString());
NetOutgoingMessage om = peer_client.CreateMessage();
om.Write((Int32)3); //unique header for debugging purposes
peer_client.Connect(peer_external, om); //tried both internal and external, no dice
Lastly, a sample case of the IPs that I'm seeing, as dumped from the server:
P1 Internal: 169.xxx.xxx.xxx:14243 //local subnet address, using the proper port
P1 External: xxx.xxx.xxx.xxx:62105 //IP address of the system, matching that from any IP testing site, but using a seemingly random port
P2 Internal: 169.xxx.xxx.xxx:14243 //same as above for the second peer
P2 External: xxx.xxx.xxx.xxx:62106
I believe that the issue is that the peer connection's external port is randomly created somewhere along the line, instead of using that which I specify when creating it. As such, it can't be forwarded in advance. I would be happy with users being required to forward a specific port, as many P2P games work this way.
In other words, I seem to have everything that I need in order to get NAT punching working properly, but I lack the knowledge of Lidgren to make it happen.
Finally, here is how I set up my peer_client:
//peer code: initialize the connection to any other peers we may connect to later
NetPeerConfiguration pconfig = new NetPeerConfiguration(appidstr_client);
pconfig.Port = 14243; //properly forwarded in router
pconfig.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
pconfig.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
pconfig.AcceptIncomingConnections = true;
peer_client = new NetPeer(pconfig);
peer_client.Start();

Did you enable introduction messages using "config.EnableMessageType(NetIncomingMessageType.NatIntroductionSuccess);"?
Is "14243" a typo? In the sample the master server listens on 14343 and the clients listen on 14242.
"This seemed to work to some degree, but it connected to the server connection on each client instead of the peer connection, and only succeeded on the sender."
I don't understand what this means. If you're using the NetPeer class there's no specific "server connection"?
Remember IPEndPoint includes the port number, in case you're storing it away somewhere you might want to set it to the port you're trying to punch open.

Related

Cannot connect to RabbitMQ from C#, None of the specified endpoints were reachable

just spined a test RabbitMQ broker in AWS, trying to connect to it but it's not working
always getting the exception None of the specified endpoints were reachable
code sample:
[Fact]
public void RabbitConnection() {
var cf = new ConnectionFactory() {
HostName = "longguid.amazonaws.com",
Password = "pass",
UserName = "user",
Port = 5671
};
// Act
var con = cf.CreateConnection();
// Assert
Assert.True(true);
}
no matter how I flip the endpoint it's not working
adding the amqps:// prefix or removing it, adding the port att the end of the hostname or through the property, use the uri property instead of hostname,set the ssl property to no matter what(tls.none, tls.1 ... etc) , it's not working at all!
tried on two systems (ubuntu, win10) 3 different networks
though I can reach the endpoint from commandline using nc and telnet
output from terminal
mohamed#xxxxxxx3:~$ nc -zv xxxxxxxxxxxxxxxxxxxxxxx.mq.xxxxx.amazonaws.com 5671
Connection to xxxxxxxxxxxxxxxxxxxxxxx.mq.xxxxx.amazonaws.com 5671 port [tcp/amqps] succeeded!
mohamed#xxxxxxx3:~$ telnet xxxxxxxxxxxxxxxxxxxxxxx.mq.xxxxx.amazonaws.com 5671
Trying 16.111.11.11...
Connected to rabbit-broker-xxxxxxxxxxxxxxxxx.elb.xx-xxxxx-1.amazonaws.com.
Escape character is '^]'.
Connection closed by foreign host.
mohamed#xxxxxxx3:~$
note: the connection while using telnet coleses after ~5 seconds.
also I can login to rabbit dashboard (different url of course) using the same credentials

Set Custom Host Name as part of changing the Endpoint Address of a Soap Client

I am presently in a scenario where I need to have multiple servers that live behind a Load Balancer talk to each other directly, and I need to communicate with specific servers for PUSH notifications. This is for a chat tool that requires users that have been moved to different servers by a load balancer to still be able to talk to one another live.
The actual pushes are being handled with Signal-R, and I have all of that working. So here is the actual complication:
Normally, this would be simple enough to do by targeting them via IP Address to bypass the load balancer. However, this is complicated because the servers expects a specific Host name or it will reject the request.
I know it is possible to do this with a WebRequest, but would like to avoid having to build a proxy if I can help it.
Here is the piece I have where I'm trying to send a global push to tell everyone across all connected servers to update their buddy lists because someone logged in or out.
private void NotifyUsersChangedGlobal()
{
List<string> addressesToNotify = ChatUsers.Select(x => x.ServerIP).Distinct().ToList();
foreach (string address in addressesToNotify)
{
ChatUplinkSoapClient client = BuildClient(address);
client.NotifyUsersChanged();
}
}
And this is the Client Builder where (I assume) I need to handle assigning the custom Host name to ride on top of the IP Address
private ChatUplinkSoapClient BuildClient(string endpointIP)
{
string relativeUrl = "/WebServices/ChatUplink.asmx";
//Turn on HTTPS
HttpBindingBase binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
//Link together the IP Address and the asmx route
EndpointAddress endpoint = new EndpointAddress(endpointIP + relativeUrl);
//Make the Client
ChatUplinkSoapClient client = new ChatUplinkSoapClient(binding, endpoint);
//Need to set Host header to "HostHeaderName", or the server will reject the request.
return client;
}
Ideas?

How to force traffic on specific network adapter

I'm developing a console app to act as a client for my web-api, such as google drive, and sky drive and etc... And I ran into a edge case: my pc has 2 connections: a Ethernet and a wifi.
The Ethernet is behind a proxy and the wifi is open.
The problem here is that the ethernet is behind a proxy, that blocks the public address for my alpha tests (in windows azure).
Since windows seems to always believe only in the ethernet, which is frustrating because if it would only try the wifi, it would work... I was wondering what can i do to force to open the socket using my second network adapter (wifi).
Combining Shtééf's anwser to How does a socket know which network interface controller to use? and the MSDN Socket reference gives the following:
Suppose the PC has two interfaces:
Wifi: 192.168.22.37
Ethernet: 192.168.1.83
Open a socket as follows:
first, use Socket.Bind(EndPoint) to select the local network interface to use;
then, use Socket.Connect(EndPoint) to connect to the remote service.
`
using System.Net.Sockets;
using System.Net;
void Main()
{
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
int anyPort = 0;
EndPoint localWifiEP = new IPEndPoint(new IPAddress(new byte[] { 192, 168, 22, 37 }), anyPort);
EndPoint localEthernetEP = new IPEndPoint(new IPAddress(new byte[] { 192, 168, 1, 82 }), anyPort);
clientSock.Bind(localWifiEP);
// Edit endpoint to connect to an other web-api
// EndPoint webApiServiceEP = new DnsEndPoint("www.myAwsomeWebApi.org", port: 80);
EndPoint webApiServiceEP = new DnsEndPoint("www.google.com", port: 80);
clientSock.Connect(webApiServiceEP);
clientSock.Close();
}
NOTE: Using a Socket like this is somewhat low level. I could not find how to easily use Sockets —bound to a local endpoint— with higher level facilities such as HttpClient or the WCF NetHttpBinding.
For the latter you could look at How to use socket based client with WCF (net.tcp) service? for pointers how to implement your own transport.
You will need to bind the outbound socket connection to the correct network interface, see this SO post:
How does a socket know which network interface controller to use?

TCP send a packet with External IP Source?

i will creat a valid TCP Packet (3 way handshake) to request on my server (real server online not vmware localhost)
My PC IP ADDRESS: 192.168.1.4
My ONLINE IP ADDRESS: 177.9.9.9
My Server IP ADDRESS: 113.x.x.x
I send a TCP Packet from my PC (177.9.9.9) to server (113.x.x.x) and success!
I can see this request showing in Wireshrak very clear with source IP is 177.9.9.9 and Destination ip is 113.x.x.x
i will write packet in C# with PCAP.NET and here is my ipV4Layer code!
IpV4Layer ipV4Layer =
new IpV4Layer
{
Source = new IpV4Address("192.168.1.4"), // My lan IP address
CurrentDestination = new IpV4Address("113.x.x.x"), // Server IP ADDRESS
HeaderChecksum = null, // Will be filled automatically.
Identification = 28104,
Options = IpV4Options.None,
Protocol = null, // Will be filled automatically.
Ttl = 128,
TypeOfService = 0,
};
NOW i want to ask, how to change 177.9.9.9 to another IP address? Not Proxy, Not socks, NOT VPN! I want to change my online IP to any IP ADDRESS, i just want to send a TCP SYN request like this and don't need server response any data, just send it with any IP address, how can do that or this way is Impossible?
Thanks for help!
If you really want to do some sort of load balancing then, go google the concept and research the viable options.
Here are some examples:
DNS based
Router/firewall/nat
Servicebus with queues, for a high level solution

get unused IP address

I need to get an available IP from the DHCP. I tried to get any ip address and start to ping the next until I reach one that doesn't respond.
public static IPAddress FindNextFree(this IPAddress address)
{
IPAddress workingAddress = address;
Ping pingSender = new Ping();
while (true)
{
byte[] localBytes = workingAddress.GetAddressBytes();
localBytes[3]++;
if (localBytes[3] > 254)
localBytes[3] = 1;
workingAddress = new IPAddress(localBytes);
if (workingAddress.Equals(address))
throw new TimeoutException("Could not find free IP address");
PingReply reply = pingSender.Send(workingAddress, 1000);
if (reply.Status != IPStatus.Success)
{
return workingAddress;
}
}
}
However, sometimes the DHCP reserves special address for some computers, so I need to get an available ip address from the dhcp.
How can I implement that in C#?
That is not the right way you are using it ,
you should request the DHCP server a new ip and then accept it ,
read about communicating with DHCP Server here
http://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol
A client application cannot make a request to the DHCP server for all available addresses.
A DHCP server can only process the following messages from a client:
DHCPDISCOVER
DHCPREQUEST
DHCPDECLINE
DHCPRELEASE
DHCPINFORM
Please see RFC 2131 - Dynamic Host Configuration Protocolfor additional information.
If you are running Windows DHCP server and you have access to the box, you can use Windows PowerShell Scripting to query the DHCP database.
Excerpt from Weekend Scripter: Parsing the DHCP Database? No Way!
Summary: Microsoft Scripting Guy, Ed Wilson, talks about a Windows PowerShell function from the DHCPServer module that permits parsing the DHCP database.
I found this app that solve the problem
http://www.centrel-solutions.com/support/tools.aspx?feature=dhcpapi

Categories