I did try to get internet IP by using GetIp method (below) but it only get one IP that's 123.22.114.5 , I restarted my modem many times but it still 123.22.114.5, please help me. (I'm using visual studio 2010 in windows 7 64bit)
(sorry about my bad english)
private string GetIp()
{
string extenalIp = "";
string whatIsMyIp = "http://automation.whatismyip.com/n09230945.asp";
string getIpRegex = #"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
WebClient wc = new WebClient();
UTF8Encoding utf8 = new UTF8Encoding();
string requestHtml = "";
try
{
requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
}
catch (Exception e)
{
// do some thing with exception
Console.WriteLine(e.Message);
}
Regex r = new Regex(getIpRegex);
Match m = r.Match(requestHtml);
if (m.Success)
{
extenalIp = m.Value.ToString();
}
wc.Dispose();
return extenalIp;
}
You would get just one IP which is your ISP's external IP address, when you request some external website like whatismyip.
All ISPs have limited static IP addresses and hosts facing the internet.
That WAN IP address is shared among many users usually.
The IP you see there is completely different from your local IP address, and hence, restarting your modem won't change it.
Related
I am building an app that communicates to a machine via TCP. The issue I have is that I can connect and all is well but once I disconnect and then try and reconnect all I get is error
The code I have in the form is
private void btn_connect_Click(object sender, EventArgs e)
{
try
{
Log(LogMsgType.Normal, String.Format("Connected on {0}\n", DateTime.Now));
string ip = (txt_ipadd_1.Text + "." + txt_ipadd_2.Text + "." + txt_ipadd_3.Text + "." + txt_ipadd_4.Text);
Log(LogMsgType.Normal, String.Format("Connecting to IP address " + ip + " Port # " + txt_port.Text +"\n"));
string con = Codenet.Connect_TCP(ip, Convert.ToInt32(txt_port.Text)); //connect to this one
Log(LogMsgType.Normal, String.Format(con + "\n"));
toolStripStatusLabel1.Text = "Connected";
btn_connect.Visible = false;
btn_disconnect.Visible = true;
ip = "";
}
catch (Exception d)
{
Log(LogMsgType.Error, String.Format("Error..... " + d.StackTrace +"\n"));
}
}
Which goes over to code from the Codenet dll which does the connection and disconnection
public static string Connect_TCP(string ip, int Port)
{
tcpclnt.Connect(ip, Port);
connection_type = "TCP";
return "Connected OK ";
}
public static void DisConnect_TCP()
{
tcpclnt.GetStream().Close();
tcpclnt.Close();
}
The error I get is:
Error..... at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port) at
comms_engine.Codenet.Connect_TCP(String ip, Int32 Port) in C:\a\code\g_com_test_1\comms_engine\Codenet.cs:line 37 at
comms_test.CommTester.btn_connect_Click(Object sender, EventArgs e) in C:\a\code\g_com_test_1\dll_test\ethernet.cs:line 98
It will not perform the tcpclnt.Connect(ip, Port) even if the ip is different.
It seems that something is still open but what I do not know as the machine has disconnected. I know that as I have UDP in it sending out how many connections it has and I can see then increase and decrease OK.
I tried "public string Connect_TCP(string ip, int Port)" and making a NEW instance of the dll befor calling the connect from the form but that did not work either.
Any ideas what I am doing wrong.
Thanks for answers so far but still I have an issue. I read the MSDN and made a test app and I can now see what is wrong but am clueless on how to fix it at the moment. I am declaring the Client as Static global so I can get it from the connect and disconnect button. I think thta this always creates new instances and I never close them. First time round the machine tells me it has diconnected bu t the app never reconnects In debug mode it falls over at client.Connect(ipEndPoint); with "InvalidOperationException was unhandled" followed by "Once the socket has been disconnected, you can only reconnect again asynchronously, and only to a different EndPoint. BeginConnect must be called on a thread that won't exit until the operation has been completed."
I guess I need to put this Client inside the btn_connect_click and get a pointer to it from inside the disconnect but how?
The full code is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.IO.Ports;
using System.Diagnostics;
using System.Threading;
namespace TCP_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private void btn_connect_Click(object sender, EventArgs e)
{
string ip = (txt_ipadd_1.Text + "." + txt_ipadd_2.Text + "." + txt_ipadd_3.Text + "." + txt_ipadd_4.Text);
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = IPAddress.Parse(ip);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, Convert.ToInt32(txt_port.Text));
// Connect the socket to the remote end point.
client.Connect(ipEndPoint);
rchTxtBx_output.AppendText("connected to " + ipEndPoint + "\n\r");
}
private void btn_disconnect_Click(object sender, EventArgs e)
{
client.Shutdown(SocketShutdown.Both);
client.Disconnect(true);
if (client.Connected)
rchTxtBx_output.AppendText("We're still connnected \n\r");
else
rchTxtBx_output.AppendText("We're disconnected \n\r");
}
}
}
Once you disconnect a TCP socket, it cannot be reconnected. You have to release the socket and create a new one. This is not just limited to the .NET TCPClient class, this is how all socket APIs work in general (WinSock, BSD, etc).
The exception to this rule is the WinSock2-specific DisconnectEx() function, which has a TF_REUSE_SOCKET flag that allows ConnectEx() (and AcceptEx()) to re-use an existing SOCKET instead of requiring a new socket to be created. But that does not apply in your situation.
In the majority of cases, once you disconnect a socket, you have to create a new socket from scratch.
Thanks for the help I have now solved it. See above for full code but below is teh snippet that makes it work. Just add client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); inside the connect button. My testing now shows it connects and disconnects and allows reconnect or connect to anothe machine. Only took me two man days to work that out with your help.
static Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private void btn_connect_Click(object sender, EventArgs e)
{
if (client.Connected)
{
client.Shutdown(SocketShutdown.Both);
client.Disconnect(true);
client.Close();
}
else
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
string ip = (txt_ipadd_1.Text + "." + txt_ipadd_2.Text + "." + txt_ipadd_3.Text + "." + txt_ipadd_4.Text);
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
When the connection is closed, underlying socket(TCPClient.Client returns socket) needs to be set for reuse . Use the Socket.Disconnect(true) instead of close to reconnect on the socket. Check the link:
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.disconnect(v=vs.90).aspx
I cannot receive a UDP packet on a Windows Azure Virtual Machine. I have done the following:
On the Virtual Machine, via Windows Firewall, I opened up Port 1234* both Inbound and Outbound for both UDP and TCP protocols. I did not add any IP exclusions. The rule should apply to Domain, Private and Public profiles. I am allowing Block Edge Traversal.
In the Azure Management Portal, I added Endpoints for my Virtual Machine instance. I added both UDP and TCP protocol endpoints. Public and Private port numbers are both 1234.
I have two test programs that I wrote: UDPSender and UDPReceiver. Using two computers on my local network, the test programs successfully sent a packet between them. (Edit: I also used UDPTester Android App to successfully send a 'trans-ISP' message to my PC running the UDPReceiver.)
Moving UDPReceiver to my Virtual Machine, I cannot successfully receive a message.
Did I miss anything in my Azure Endpoint configuration? Please Help!
* Port Number changed to protect the innocent.
Test Program Code Below...
UDPSender:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textMessage.Text = "Knock, knock";
textIP.Text = "xxx.xxx.xxx.xxx";
textPort.Text = "1234";
}
private void buttonSend_Click(object sender, EventArgs e)
{
UdpClient udpClient = new UdpClient(textIP.Text, Convert.ToInt32(textPort.Text));
Byte[] sendBytes = Encoding.ASCII.GetBytes(textMessage.Text);
try
{
udpClient.Send(sendBytes, sendBytes.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
UDPReceiver:
private static void Main(string[] args)
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(1234);
while (true)
{
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
System.Net.IPEndPoint RemoteIpEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
string messageOut = String.Format("[{0},{1}]#[{2}]: {3}",
RemoteIpEndPoint.Address.ToString(),
RemoteIpEndPoint.Port.ToString(),
DateTime.Now,
returnData.ToString());
Console.WriteLine(messageOut);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
The code looks correct. I compared it against my implementation. Here are the key sections for reference:
Your csdef should have the correct port protocol. You said you did this through the portal, but confirm the settings saved:
<Endpoints>
<InputEndpoint name="UdpEndpoint" protocol="udp" port="8080" localPort="8080" />
</Endpoints>
(from https://github.com/ytechie/LogHub/blob/master/Microsoft.LogHub.Cloud/ServiceDefinition.csdef)
And listening on the correct port was as easy as:
var endPoint = new IPEndPoint(IPAddress.Any, 0);
var udp = new UdpClient(8080);
(from https://github.com/ytechie/LogHub/blob/master/Microsoft.LogHub/Global.asax.cs)
Feel free to take a look at my implementation and look for differences. I did notice that you're using the synchronous version of "Receive", but that shouldn't matter.
I'm also curious if this is PaaS or IaaS. In either case, you'll need to hit against the load balanced endpoint, and not an internal endpoint which would be inaccessible from the internet.
hello I connect my device android to printers, of the way follows.
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bluetakebt220 =
bluetoothAdapter.getRemoteDevice(obj.getMac().toString());
BluetoothSocket mBTsocket= null;
bluetoothAdapter.cancelDiscovery();
UUID num = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
mBTsocket = bluetakebt220.createRfcommSocketToServiceRecord(num);
mBTsocket.connect();
this works well for for most devices, but some do not connected, ¿that can be due?
The most obvious reason I can think of is the UUID's do not match up. If you are making a generic app you need to have the UUID of each printer. This can be done in the form of a case switch statement.
Code
switch(Mac Address) {
case (Mac Address 1)
UUID = xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
case (Mac Address 2):
UUID = xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
default:
UUID = 00001101-0000-1000-8000-00805F9B34FB;
The reason why most of the time your connections works is because 00001101-0000-1000-8000-00805F9B34FB is the generic ID for most off shelf hardware devices (keyboards,mouses,printers,scanners etc). The minute your UUID does not match a connection cannot occur. Read this for more info about UUID's.
the device acts equal, simply does not establish proper connection , but yes allow write in
Here is the code if someone can help
UUID num = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bluetakebt220 = bluetoothAdapter.getRemoteDevice(obj.getMac().toString());//PRINTER ADAPTER FOR LPT BLUETAKE BT220
BluetoothSocket mBTsocket= null;
mBTsocket = bluetakebt220.createRfcommSocketToServiceRecord(num);
bluetoothAdapter.cancelDiscovery();
mBTsocket.connect();
OutputStream os = **mBTsocket**.getOutputStream();
os.flush();
byte[] CPCLFormat = null;
PCLFormat = objImpresion.getTexto().getBytes("utf-8");
os.write(CPCLFormat);//se imprime el texto
os.flush();
os.close();
.I simply comment msocket.isConnected and write directly after open connection. i don´t why happen
Writing to remote MSMQ seems to be working on/off. I am not sure what is wrong and what else to do to confirm sending.
I am reluctant to setup some kind of ack. It seems to be an overkill.
using (var queue = new MessageQueue(queueName, QueueAccessMode.Send))
{
var messageQueueTransaction = new MessageQueueTransaction();
messageQueueTransaction.Begin();
try
{
queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(EmailMessage) });
var msg = new Message();
msg.Label = emailMessage.Subject;
msg.Body = emailMessage;
queue.Send(msg, messageQueueTransaction);
messageQueueTransaction.Commit();
}
catch (Exception e)
{
LoggerLib.Logger.ErrorException(e, "Error Sending Email using MSMQ", emailMessage);
messageQueueTransaction.Abort();
}
finally
{
queue.Close();
}
}
The Connection string for MSMQ is in the format of:"FormatName:DIRECT=OS:FULLMACHINENAME\private$\emailmessagequeue"
Also, I used "FormatName:DIRECT:TCP:IPAddress\private$\emailmessagequeue".
It works without a glitch when I ran it locally. So, I allowed Everyone to have Full access and It still doesn't work.
Any ideas?
The port number 1801 was blocked. That resolved it. –
Hi i have got a TCP/IP Socket project.
i can send string messages to Server with Client side and i can get responses from server.
But getting one string message and sending only one string (or any other object).I wanna Encode Personel class to Byte array after send to Clients from server side.And Decode it. than get values from my class.
//SERVER SIDE CODE Connect() starts at on form load
private void Connect()
{
// start listen socket
dinleyiciSoket = new TcpListener(System.Net.IPAddress.Any, 10048);
dinleyiciSoket.Start();
Socket istemciSoketi = dinleyiciSoket.AcceptSocket();
NetworkStream agAkisi = new NetworkStream(istemciSoketi);
BinaryReader binaryOkuyucu = new BinaryReader(agAkisi);
BinaryWriter binaryYazici = new BinaryWriter(agAkisi);
string alinanMetin = binaryOkuyucu.ReadString();
MessageBox.Show(alinanMetin, "Yeni Genelge", MessageBoxButtons.OK);
binaryYazici.Write(true);
dinleyiciSoket.Stop();
Connect();
}
////////// CLIENT SIDE //////////////
private string IpAdresi(string host)
{
string address = "";
IPAddress[] addresslist = Dns.GetHostAddresses(host);
foreach (IPAddress theaddress in addresslist)
{
if (theaddress.AddressFamily == AddressFamily.InterNetwork)
{
address = theaddress.ToString();
}
}
return address;
}
bool onay;
private void button1_Click(object sender, EventArgs e)
{
//create socket connection
Socket istemciBaglantisi = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Bağlantıyı gerçekleştir
if (istemciBaglantisi.Connected != true)
{
istemciBaglantisi.Connect(IPAddress.Parse(IpAdresi(txtHost.Text)), 10048);
}
agAkisi = new NetworkStream(istemciBaglantisi);
binaryYazici = new BinaryWriter(agAkisi);
binaryOkuyucu = new BinaryReader(agAkisi);
binaryYazici.Write(txtMesaj.Text);
onay = binaryOkuyucu.ReadBoolean();
MessageBox.Show(onay.ToString());
istemciBaglantisi.Close();
}
Take a look at object serialization. See here for examples. That should get you going in the right direction.
You can use google's protocol buffers. It is a fast and compact mechanism for serializing objects. There are two implementations on .NET: protobuf-net and protobuf.
I'd use object serialization or XmlSerialization, both available in .NET. I would not look at Google's protocol buffers, because that RPC encoding has little advantage over what's already in .NET, but it is obscure, especially in the .NET world, and especially now. I wouldn't bet on it becoming mainstream for .net devs. As a result, you will only make your code harder to maintain by using this RPC encoding.
I don't really see the need for protobufs when the apps that are interconnecting are homogeneous, and are NOT on the scale of Google's datacenters. I also don't see the need even when heterogeneity is the rule, because we already have JSON and XML. They are both readable and serviceable, where protobufs are not.
In any case .NET has what you need for this, built-in.