473,769 Members | 1,803 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getting client ip in sock-client on server

The code of classes given below is for server to which clients connect
i want to get ip address of client which has connected
pls help how can i get
//listen class
public class listen
{
TcpListener server=null;
Thread tcpthread=null;
client[] cl=new client[3];

public listen()
{
//
// TODO: Add constructor logic here
//
}
public void startlisten()
{
Int32 port = 3310;
IPAddress localAddr = IPAddress.Parse ("192.168.0.6") ;

// TcpListener server = new TcpListener(por t);
server = new TcpListener(loc alAddr, port);

// Start listening for client requests.
server.Start();
// Enter the listening loop.
for(int i=0;i<3;i++)
{
cl[i]=new client();
cl[i].status=true;
}

Boolean flag;
while(true)
{
try
{
flag=false;
// Perform a blocking call to accept requests.
// You could also user server.AcceptSo cket() here.
for(int i=0;i<3;i++)
{
if(cl[i].status==true)
{
cl[i]= new client(server.A cceptTcpClient( ));
tcpthread=new Thread(new ThreadStart(cl[i].getClient));
tcpthread.Start ();
flag=true;
break;
}
}
if(flag!=true)
{
//MessageBox.Show ("All Clients Busy");

}


}
catch(Exception se)
{

}
}

}
public void stoplisten()
{
server.Stop();
}
}


//client class
public class client
{
TcpClient tcpClient;
public Boolean status;
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
IPAddress localAddr = IPAddress.Parse ("192.168.0.6") ;

public client()
{ //
// TODO: Add constructor logic here
//
//status=true;
}
public client(TcpClien t Client)
{
tcpClient =Client;
//
// TODO: Add constructor logic here
//
status=false;
}
public void getClient()
{
try
{
data = null;
// Get a stream object for reading and writing
NetworkStream stream = tcpClient.GetSt ream();
int i;
// Loop to receive all the data sent by the client.
while((i = stream.Read(byt es, 0, bytes.Length))! =0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Enc oding.ASCII.Get String(bytes, 0, i);
// Process the data sent by the client.
string replyMsg = data;
clamdCommand x=new clamdCommand();
replyMsg=x.Comm and(replyMsg);
int
lowerport=int.P arse(Configurat ionSettings.App Settings.Get("l owerport"));
int
upperport=int.P arse(Configurat ionSettings.App Settings.Get("u pperport"));
for(int y=lowerport;y<u pperport;y++)
{
if(replyMsg==y. ToString())
{
replyMsg=replyM sg+"\r\n\0";
byte[] msg = System.Text.Enc oding.ASCII.Get Bytes(replyMsg) ;
// Send back a response.
stream.Write(ms g, 0, msg.Length);
TcpListener listener=new TcpListener(loc alAddr,y);
listener.Start( );
// Buffer for reading data
Byte[] bs = new Byte[256];
String ds = null;
// Enter the listening loop.
while(true)
{ // Perform a blocking call to accept requests.
// You could also user server.AcceptSo cket() here.
TcpClient bufferclient = listener.Accept TcpClient();
ds = null;
// Get a stream object for reading and writing
NetworkStream strm = bufferclient.Ge tStream();
int l;
// Loop to receive all the data sent by the client.
while((l = strm.Read(bs, 0, bs.Length))!=0)
{ ds = System.Text.Enc oding.ASCII.Get String(bs, 0, l);
// Process the data sent by the client.
clamresults obj=new clamresults();
ds=obj.loadData base("STREAM",d s);

replyMsg=ds;
bufferclient.Cl ose();
break;
}
listener.Stop() ;
x.freeport(y-lowerport);
break;
} break;
}

}
replyMsg=replyM sg+"\r\n\0";
byte[] msgs = System.Text.Enc oding.ASCII.Get Bytes(replyMsg) ;
// Send back a response.
stream.Write(ms gs, 0, msgs.Length);

}
}
catch(Exception se)
{
MessageBox.Show (se.ToString()) ;

}
// Shutdown and end connection
finally
{
tcpClient.Close ();
status=true;
}
}

}
Jan 19 '06
14 4451

""TerryFei" " <v-******@online.m icrosoft.com> wrote in message
news:9G******** ******@TK2MSFTN GXA02.phx.gbl.. .
Hi Ankit,

In this current situation, I suggest you could try to invoke getpeername /
getsockname using PInvoke mechanism. On a connected socket, getpeername
will give you the remote address and getsockname will give you the local
address for the connection. We could use Socket.Handle Property to get the
socket handle and pass it into these API as parameters.

I hope the above inforamtion is helpful for you.If you have any questions
or concerns, please let me know. Thanks again and have a nice day!


....

The problem is that TcpClient does not expose underlying socket. Socket
TcpClient.Clien t is protected property (holds underlying socket). I suspect
OP could get this using reflection (I heard this is possible using
reflection, but haven't tried it myself and it is bad practice to do this of
course). Socket has RemoteEndPoint property, so it should not be needed to
PInvoke. Haven't tested it, though. Or maybe I missed the original problem?

Regards,
Goran
Jan 20 '06 #11
can u give me some sample code
how i can get remote ip without changing much of my present code
"Goran Sliskovic" <gs******@yahoo .com> wrote in message
news:%2******** *******@tk2msft ngp13.phx.gbl.. .

""TerryFei" " <v-******@online.m icrosoft.com> wrote in message
news:9G******** ******@TK2MSFTN GXA02.phx.gbl.. .
Hi Ankit,

In this current situation, I suggest you could try to invoke getpeername
/
getsockname using PInvoke mechanism. On a connected socket, getpeername
will give you the remote address and getsockname will give you the local
address for the connection. We could use Socket.Handle Property to get
the
socket handle and pass it into these API as parameters.

I hope the above inforamtion is helpful for you.If you have any questions
or concerns, please let me know. Thanks again and have a nice day!


...

The problem is that TcpClient does not expose underlying socket. Socket
TcpClient.Clien t is protected property (holds underlying socket). I
suspect
OP could get this using reflection (I heard this is possible using
reflection, but haven't tried it myself and it is bad practice to do this
of
course). Socket has RemoteEndPoint property, so it should not be needed to
PInvoke. Haven't tested it, though. Or maybe I missed the original
problem?

Regards,
Goran

Jan 21 '06 #12

"Ankit Aneja" <ef*****@newsgr oups.nospam> wrote in message
news:eb******** ******@TK2MSFTN GP14.phx.gbl...
can u give me some sample code
how i can get remote ip without changing much of my present code

....

Hi,

Here it is:
<CUT>
using System;
using System.Reflecti on;
using System.Reflecti on.Emit;

using System.Net;
using System.Net.Sock ets;

namespace ConsoleApplicat ion1 {
public class Test {
public static void Main() {
TcpListener tcpListener = new TcpListener(IPA ddress.Any, 10000);
tcpListener.Sta rt();
TcpClient client = tcpListener.Acc eptTcpClient();
Type tcpClientType = typeof(TcpClien t);
//get value of protected TCPClient property Client that holds
socket...
Socket clientSocket =
(Socket)tcpClie ntType.InvokeMe mber("Client", BindingFlags.Ge tProperty |
BindingFlags.No nPublic | BindingFlags.In stance , null, client, null);
//socket RemoteEndpoint is address of connected tcpClinet...
IPEndPoint endPoint = (IPEndPoint) clientSocket.Re moteEndPoint;
string remotAddr = endPoint.Addres s.ToString();
}
}
}
</CUT>

Please note that such thing is considered bad practice and potentialy
dangerous. No guarantees.

Regards,
Goran

Jan 21 '06 #13
Hi Goran,
Socket has RemoteEndPoint property, so it should not be needed to
PInvoke. Haven't tested it Thanks for your reply! Yes, Socket has RemoteEndPoint property and we could
access relevant address with it in theory. However customer has tried it
and failed. So I suggest use PInvoke to achieve this goal.

Best Regards,

Terry Fei[MSFT]
Microsoft Community Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

--------------------
From: "Goran Sliskovic" <gs******@yahoo .com>
References: <uq************ **@TK2MSFTNGP14 .phx.gbl> <dq**********@s unce.iskon.hr> <Oz************ **@TK2MSFTNGP15 .phx.gbl>
<e0************ **@TK2MSFTNGP10 .phx.gbl>
<Ox************ **@TK2MSFTNGP09 .phx.gbl>
<9G************ **@TK2MSFTNGXA0 2.phx.gbl>Subject: Re: getting client ip in sock-client on server
Date: Fri, 20 Jan 2006 14:03:53 +0100
Lines: 27
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2800.1506
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1506
Message-ID: <#q************ *@tk2msftngp13. phx.gbl>
Newsgroups: microsoft.publi c.dotnet.langua ges.csharp
NNTP-Posting-Host: 194-152-209-27.adsl.net.t-com.hr 194.152.209.27
Path: TK2MSFTNGXA02.p hx.gbl!TK2MSFTN GP08.phx.gbl!tk 2msftngp13.phx. gbl
Xref: TK2MSFTNGXA02.p hx.gbl microsoft.publi c.dotnet.langua ges.csharp:3799 94
X-Tomcat-NG: microsoft.publi c.dotnet.langua ges.csharp
""TerryFei" " <v-******@online.m icrosoft.com> wrote in message
news:9G******* *******@TK2MSFT NGXA02.phx.gbl. ..
Hi Ankit,

In this current situation, I suggest you could try to invoke getpeername
/ getsockname using PInvoke mechanism. On a connected socket, getpeername
will give you the remote address and getsockname will give you the local
address for the connection. We could use Socket.Handle Property to get the socket handle and pass it into these API as parameters.

I hope the above inforamtion is helpful for you.If you have any questions
or concerns, please let me know. Thanks again and have a nice day!


...

The problem is that TcpClient does not expose underlying socket. Socket
TcpClient.Clie nt is protected property (holds underlying socket). I suspect
OP could get this using reflection (I heard this is possible using
reflection, but haven't tried it myself and it is bad practice to do this

ofcourse). Socket has RemoteEndPoint property, so it should not be needed to
PInvoke. Haven't tested it, though. Or maybe I missed the original problem?

Regards,
Goran


Jan 23 '06 #14

""TerryFei" " <v-******@online.m icrosoft.com> wrote in message
news:3n******** ********@TK2MSF TNGXA02.phx.gbl ...
Hi Goran,
Socket has RemoteEndPoint property, so it should not be needed to
PInvoke. Haven't tested it
Thanks for your reply! Yes, Socket has RemoteEndPoint property and we

could access relevant address with it in theory. However customer has tried it
and failed. So I suggest use PInvoke to achieve this goal.

....

Hi,

I posted example with tcpclient/remoteendpoint that works (no my lan),
framework 1.1. Though I can guess there may be problems in non-trivial
network setups (NAT for example).

Regards,
Goran
Jan 23 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2318
by: MJL | last post by:
This is a mysql/php question (but a little more on the mysql side.) The two are so closely related these days, I thought it would be ok to ask here. I installed on my Suse Linux system mysql 4.0 using an rpm. I also installed all of the appropriate PHP 4.3 and Apache 2.0 rpms. I set my socket path in my.cnf to /tmp/mysql.sock. I then, just to be safe and thorough, copied this my.cnf to ~/.my.cnf and to the /var/lib/mysql directory...
0
1863
by: Oliver Etzel - GoodnGo.COM | last post by:
Hello all, after Installing mysql I started the mysql daemon.. The I tried to log in to my mysql database and got the message could not find mysql.sock in /tmp. In the mysql-configuration file /etc/my.cnf (in my redhat system 8.0) I changed the place for the socket file from "socket=/var/lib/mysql/mysql.sock" to "socket=/tmp/mysql.sock".
0
1457
by: Oliver Etzel - GoodnGo.COM | last post by:
Hello all, after Installing mysql I started the mysql daemon.. The I tried to log in to my mysql database and got the message could not find mysql.sock in /tmp. In the mysql-configuration file /etc/my.cnf (in my redhat system 8.0) I changed the place for the socket file from "socket=/var/lib/mysql/mysql.sock" to "socket=/tmp/mysql.sock".
0
1451
by: Oliver Etzel - GoodnGo.COM | last post by:
Hello all, after Installing mysql I started the mysql daemon.. Then I tried to log in to my mysql database and got the message could not find mysql.sock in /tmp. In the mysql-configuration file /etc/my.cnf (in my redhat system 8.0) I changed the place for the socket file from "socket=/var/lib/mysql/mysql.sock" to "socket=/tmp/mysql.sock". That doesn´t work.
1
3891
by: JW | last post by:
Hi all, I was fine running mysql, and for some reason, after the most recent reboot of my machine, I get the following error and I try the following subsequent commands to try to figure things out: # mysql ERROR 2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) # mysqld_safe
0
1561
by: DevBoy | last post by:
I installed the base MySQL 4.0 with Suse Linux and I try and start it and I get anb issue with the fact that mysql.sock file does not exist in /etc..../mysql/mysql.sock I created a file and made sure the owner is mysql. Can anyone share a template for what this file should look like?
5
2647
by: OZ | last post by:
the serproxy claim itself a multi-thread proxy thing. I have sent email to write the original writer and there is no replay after 3 weeks. my configuration and setting are good. http://www.lspace.nildram.co.uk/freeware.html I installed it in rh 9.0 I found it is single user only.
1
1814
by: vabh | last post by:
Help from there, i want the IP Address of all computers which are connected in LAN with me. Its really urgent for me. I using one kind of coding which returns me IP Address of only one computer, but when i enter a Computer Name. The source code of that one is as follows: ******************************************************************************************** Dim s1, s2 As String Dim IPHost As IPHostEntry =...
2
2651
by: Roopesh | last post by:
Hi, I am using poplib's retr() to fetch mails from my gmail account. It works fine, in some cases it gets stuck inside the retr() method and does not come out. From the logs I could find that when retr() is called, it stops executing further statements, nor does it throw an exceptions but simply stops. My code is roughly like the foll:
185
7122
by: jacob navia | last post by:
Hi We are rewriting the libc for the 64 bit version of lcc-win and we have added a new field in the FILE structure: char *FileName; fopen() will save the file name and an accessor function will return the file name given a FILE *. Questions: What would be the best name for this function?
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10212
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10047
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.