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?
Related
I have an event hubs instance with a “test” eventhub.
I can connect to this and publish messages with the native client "Azure.Messaging.EventHubs"
However when I try to connect with the Confluent.Kafka (v1.1.0) client I get
“Unknown error (after 21286ms in state CONNECT)”
%3|1655301022.374|ERROR|rdkafka#producer-1|
[thrd:sasl_plaintext://my-event-hub-namespace.servicebus.windows.net:9093/bootstra]:
1/1 brokers are down
I'm setting the producer config, and creating producer as below
var config = new ProducerConfig
{
BootstrapServers = "my-eventhub-namespace.servicebus.windows.net:9093",
SecurityProtocol = SecurityProtocol.SaslSsl,
SaslMechanism = SaslMechanism.Plain,
SaslUsername = "$ConnectionString",
SaslPassword = "Endpoint=sb://my-eventhub-namespace.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=MySharedAccessKey==",
};
using (var producer = new ProducerBuilder<long, string>(config).SetKeySerializer(Serializers.Int64).SetValueSerializer(Serializers.Utf8).Build())
{
Any ideas as to where I'm going wrong?
Update :
When connecting with the native client it's connecting using WebSockets, so it's probably networking/firewall issue.
Thanks for your time.
A couple of things to try
Firewall check for EH endpoint. Make sure the client can connect to my-eventhub-namespace.servicebus.windows.net:9093.
Try with a namespace-level connection string if you used entity-level SAS.
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.
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
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
Im using http://managedupnp.codeplex.com/ API to open up a port using UPNP on my NetGear DG834g ROUTER with the following code..
public void UPNPOpenPort(int port)
{
Services lsServices;
lsServices = Discovery.FindServices("urn:schemas-upnp-org:service:WANPPPConnection:1");
if (lsServices.Count > 0)
using (Service lsService = lsServices[0])
{
try
{
object[] loObj = new object[] { "", port, "TCP", port, "10.0.0.100", true, "Custom Mapping", 0 };
lsService.InvokeAction("AddPortMapping", loObj);
}
catch (Exception loE)
{
MessageBox.Show(
String.Format(
"{0}: HTTPSTATUS: {1}",
loE.Message,
lsService.LastTransportStatus));
}
}
else
{
MessageBox.Show("Doh No Router Found");
return;
}
}
I have a service host with a NetTCP binding with the same port im feeding into the sub routine to set the UPNP forwarding and I can see an active UPNP record on the router configuration. I can see the port is listening on my local machine and other PC's on my LAN can connect to the port however using an online Port checker it shows as closed, even though the Router says that it should be forwarding to the correct internal IP.
Does anyone have any ideas or am i missing something?
Best Regards,
Christopher Leach
Yes. I performed a factory restore on the router, enabled UPnP, opened the service host and created a forward. It worked.
Even Teredo decided to come online.
Its great to know from a beginners perspective that its not always your codes(your understanding) fault. Sometimes its your hardware.
Thanks,
Christopher Leach