Client cannot access server which bind loopback address in C# - sockets

Now a socket in server side binds 192.168.1.69:9000,and then start to listen. Client connects the server using 127.0.0.1:9000. But fail. However,it works when client connect the server using 192.168.1.69:9000. Client and server are both running on the same commputer.My question is: it should be successful When client using loopback address connect the server, but fail.Why?
Server Code:
this.pro_ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.pro_ListenSocket.ReceiveBufferSize = this.pro_BufferSize;
this.pro_ListenSocket.SendBufferSize = this.pro_BufferSize;
try
{
this.pro_ListenSocket.Bind(new IPEndPoint(this.pro_ServerIP, this.pro_Port));
}
catch (SocketException socketError)
{
return false;
}
catch (Exception)
{
return false;
}
try
{
this.pro_OnRunning = true;
this.pro_ListenSocket.Listen(500);
this.StartToAcceptClient(this.pro_ListenSocket);
}
catch (Exception ex)
{
return false;
}

Loopback is represented as a network adapter, just like any other. You have set your server to only listen for connections on the adapter at 192.168.1.69. If you want your server to listen on additional adapters, the easiest approach is to make it available on all available adapters by specifying the address IPAddress.Any (0.0.0.0).
this.pro_ListenSocket.Bind(new IPEndPoint(IPAddress.Any, this.pro_Port));

Related

How can I get devices name after gathering all the IP addresses connected in a network? Flutter

I am using lan_scanner flutter package to gather IP Addresses of a network.I want to also get the hostname of each particular address. Any ideas on how can I achieve that?
I tried using some other packages but to no avail.
you can connect to that device and ask for it's hostname
first add a server socket to listen for clients (devices)
const int port = 7575;
try {
ServerSocket server = await ServerSocket.bind(deviceIp, port);
server.listen((client) {
client.listen((data) {
final ip = client.remoteAddress.address;
final hostname = String.fromCharCodes(data);
print("hostname of $ip is $hostname");
});
});
} on SocketException catch(_) {
print('failed to create a server socket');
}
then for each device connect to the server and send the device hostname
try {
Socket client = await Socket.connect(targetIp, port);
client.write(Platform.localHostname);
client.destroy();
} on SocketException catch(_) {
print('failed to connect to the server');
}

NetCore IPV6 socket connection fails on linux-arm

I am trying to establish an IPV6 socket connection with net-core 3.0 on a linux-arm platform (raspberry pi).
At the time when I try to bind the socket to the local ethernet adapter an Exception ((22): Invalid argument [fe80::211c:bf90:fbbf:9800]:5400) is thrown.
When i try the same on my windows development machine (with a different link-local ip), everything works fine.
IPV4 socket connection is also possible on both, my windows development machine and on the target linux-arm platform.
To the source code:
I used the socket example of microsoft as a base and changed the IPV4 into an IPV6 address.
The exception is thrown after the "Bind" method.
Here is the client side code:
//definet the target endpoint
IPAddress ipAddress;
IPAddress.TryParse("fe80::211c:bf90:fbbf:9800", out ipAddress);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 5400);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily ,SocketType.Stream, ProtocolType.Tcp);
//bind to the local network interface
IPAddress localIp;
IPAddress.TryParse("fe80::833:e68b:32ee:4c39", out localIp);
EndPoint localEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
sender.Bind(localEndPoint);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
The input of Ron was in fact the missing part. Hence the target endpoint IpAddress has to provided with the ScopeId (NIC Nr).
//definet the target endpoint
IPAddress ipAddress;
IPAddress.TryParse("fe80::211c:bf90:fbbf:9800", out ipAddress);
ipAddress.ScopeId = scopeId;
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 5400);
To the scope ID of the first link local address for example this code can be used:
private static long GetScopeIdForHostLinkLocal()
{
IPAddress firstLinkLocal = null;
var info = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in info)
{
var ipProps = nic.GetIPProperties();
var uniAddresses = ipProps.UnicastAddresses;
foreach (UnicastIPAddressInformation addressInfo in uniAddresses)
{
if (addressInfo.Address.IsIPv6LinkLocal)
{
firstLinkLocal = addressInfo.Address;
break;
}
}
if (firstLinkLocal != null)
{
break;
}
}
if (firstLinkLocal != null)
{
return firstLinkLocal.ScopeId;
}
else
{
return -1;
}
}

Not able to connet to ejabberd server through smack

I am setting up a chat service using ejabberd and building an XMPP client for android devices using smack.
Here are some important details.
server OS: ubuntu 18.04
server hosted as localhost (jid format: alice#localhost).
server system IP : 192.168.4.162
Client:
Smack 4.3.1
Using external phone through USB debugging : Nokia 3.1 Plus.
Here is my code
Here are some of the configurations I tried.
private class MyLoginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
// Create a connection to the jabber.org server.
InetAddress addr = null;
try{
addr = InetAddress.getByName("192.168.4.162");
}catch(UnknownHostException e){
e.printStackTrace();
}
XMPPTCPConnectionConfiguration config = null;
DomainBareJid serviceName = null;
try{
serviceName = JidCreate.domainBareFrom("localhost");
System.out.println("serviceName: "+serviceName);
}catch(XmppStringprepException e){
e.printStackTrace();
}
HostnameVerifier verifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", PORT, SERVICE);
try{
config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("alice", "9009")
.setHost("192.168.4.162")
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setXmppDomain("localhost")
.setHostnameVerifier(verifier)
.setHostAddress(addr)
.setPort(5222)
.build();
}catch(XmppStringprepException e){
e.printStackTrace();
}
AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);
try {
System.out.println("Connecting......."); AndroidUsingLinkProperties.setup(getApplicationContext());
conn1.connect().login();
if(conn1.isConnected()) {
Log.w("app", "conn done");
}
conn1.login();
if(conn1.isAuthenticated()) {
Log.w("app", "Auth done");
}
}
catch (Exception e) {
Log.w("app", e.toString());
}
return "";
}
#Override
protected void onPostExecute(String result) {
}
}
The configurations i tried above the result is:
org.jivesoftware.smack.SmackException$ConnectionException: The following addresses failed: '192.168.4.162:5222' failed because: /192.168.4.162 exception: java.net.ConnectException: failed to connect to /192.168.4.162 (port 5222) from /192.168.4.182 (port 39568) after 30000ms: isConnected failed: EHOSTUNREACH (No route to host)
however I am successfully able to build a connection to my server through any other client(psi, gajim, My web app(BOSH connection)).
following may help if networking is the issue:
$ nmap localhost
Starting Nmap 7.80 ( https://nmap.org ) at 2019-08-28 18:00 IST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000056s latency).
Not shown: 992 closed ports
PORT STATE SERVICE
111/tcp open rpcbind
139/tcp open netbios-ssn
445/tcp open microsoft-ds
631/tcp open ipp
5222/tcp open xmpp-client
5269/tcp open xmpp-server
5280/tcp open xmpp-bosh
8600/tcp open asterix
Nmap done: 1 IP address (1 host up) scanned in 0.09 seconds
I have been there and I found out the accidentally my phone and my ejabberd server were on different network. They should be on the same network as in this case. Make sure you are on same network and this error should go away.

Error while connecting to openfire server using asmack 4.0.2

Im trying to connect to Openfire Server using Asmack library 4.0.2.Im failing to get connected to the server even though i had provided correct ip address with the port.
public static final String HOST = "192.168.1.100";
public static final int PORT = 9090;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connect();
}
public void connect(){
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>(){
#Override
protected Boolean doInBackground(Void... arg0){
boolean isConnected = false;
ConnectionConfiguration config = new ConnectionConfiguration(HOST,PORT);
config.setReconnectionAllowed(true);
config.setSecurityMode(SecurityMode.disabled);
config.setDebuggerEnabled(true);
XMPPConnection connection = new XMPPTCPConnection(config);
try{
connection.connect();
Log.i("XMPPChatDemoActivity","Connected to " + connection.getHost());
isConnected = true;
} catch (IOException e){
Log.e("XMPPIOExceptionj", e.toString());
} catch (SmackException e){
Log.e("XMPPSmackException", e.toString()+" Host:"+connection.getHost()+"Port:"+connection.getPort());
} catch (XMPPException e){
Log.e("XMPPChatDemoActivity", "Failed to connect to "
+ connection.getHost());
Log.e("XMPPChatDemoActivity", e.toString());
}
return isConnected;
}
};
connectionThread.execute();
}
And im getting the following error possibly because Host and Port are getting assigned null and 0 respectively even though i had assigned them correctly.Pls help me in
sorting out this connection prob.
08-12 22:10:20.496: E/XMPPSmackException(4341):org.jivesoftware.smack.SmackException$NoResponseException Host:nullPort:0
Can you confirm that port 9090 is the correct port for XMPP protocol? Default install of Openfire will set port 9090 to be used for accessing the HTTP based configuration console. I recommend you try connecting to the port for XMPP connections as specified on the main index page of the Openfire configuration console (Listed below "Server Ports").
The following is taken from the Openfire configuration console:
5222 The standard port for clients to connect to the server. Connections may or may not be encrypted. You can update the security settings for this port.
I think your Host adress is wrong too, you must use the adress to connect openfire server. It must be "127.0.0.1" or just write "localhost". and the port is 5222 to be able to talk from client to server.

j2me-j2se socket connection

I am working on a j2me application that sends data to PC over WiFi using Sockets. What should be the server address? i.e. What should I use instead of 'localhost' in the code below?
Client Code(j2me):
SocketConnection sc = (SocketConnection)
Connector.open("socket://localhost:9002");
DataOutputStream os = null;
try{
os = sc.openDataOutputStream();
os.writeUTF("Test Dama");
} finally{
sc.close();
os.close();
}
Server Code(j2se):
ServerSocket echoServer = null;
String line;
DataInputStream is;
Socket clientSocket = null;
try {
echoServer = new ServerSocket(9002);
}
catch (IOException e) {
System.out.println(e);
}
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
line = is.readUTF();
System.out.println("Received:"+line);
}
catch (IOException e) {
System.out.println(e);
}
That depends on the ip/domain of the server.
If you are running things on a local network (in your home/office) then just find out what is the ip of the machine running the server code.
In linux systems you can find that with the command ifconfig, then in the output the ip address is under inet addr. In windows systems use ipconfig /all.
Once you have the ip of the machine running the server, just put that instead of the localhost that you are using in the client.
If you want this to work on the public network though, you'll have to run the server code on a machine that has a static ip (or use dynamic DNS).