Get the server name and ip address in C# 2010
I want to get the IP address of the server. The following code comes from:
public static void DoGetHostEntry(string hostname)
{
IPHostEntry host;
host = Dns.GetHostEntry(hostname);
MessageBox.Show("GetHostEntry({0}) returns:"+ hostname);
foreach (IPAddress ip in host.AddressList)
{
MessageBox.Show(" {0}"+ ip.ToString());
}
}
This code must know the name of the server computer.
AddressFamily in System.Net.IPAddress
System.Net.IPAddress i;
string HostName = i.AddressFamily.ToString();
Error ------------->Use of unassigned local variable 'i'
How can I get the name of the server computer?
To get the host name you can do the following:
string name = System.Net.Dns.GetHostName();
If you want the hostname and (first IPv4) IP of your computer use the following:
string name = System.Net.Dns.GetHostName();
host = System.Net.Dns.GetHostEntry(name);
System.Net.IPAddress ip = host.AddressList.Where(n => n.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).First();
The name and the ip will hold the info for the local computer.
The server could then send out the ip via a udp multicast and the client on the network would just join a known multicast address that is not specific to the server.
multicast example.
First of all, you need to figure out for yourself that error(unassigned local variable) and learn why it is coming(it is very basic), before looking for some magical code that will do the job for you.
And secondly, there is no magical code. I am no socket programmer but it seems to me that in your application running on the client machines, you need to hardcode the name of your server. If you don't want to do that, program in such a way that only your server machine will listen on a particular port and all client machines will listen on a different port. Thus, each machine in the LAN can enumerate over the available machines and establish/determine the client server connection/relation for the first time. and that approach is still very ugly unless you are writing a virus or something.
public string[] ServerName()
{
string[] strIP = DisplayIPAddresses();
int CountIP = 0;
for (int i = 0; i < strIP.Length; i++)
{
if (strIP[i] != null)
CountIP++;
}
string[] name = new string[CountIP];
for (int i = 0; i < strIP.Length; i++)
{
if (strIP[i] != null)
{
try
{
name[i] = System.Net.Dns.GetHostEntry(strIP[i]).HostName;
}
catch
{
continue;
}
}
}
return name;
}
public string[] DisplayIPAddresses()
{
StringBuilder sb = new StringBuilder();
// Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
int i = -1;
string[] s = new string[networkInterfaces.Length];
foreach (NetworkInterface network in networkInterfaces)
{
i++;
if (network.OperationalStatus == OperationalStatus.Up)
{
if (network.NetworkInterfaceType == NetworkInterfaceType.Tunnel) continue;
if (network.NetworkInterfaceType == NetworkInterfaceType.Tunnel) continue;
//GatewayIPAddressInformationCollection GATE = network.GetIPProperties().GatewayAddresses;
// Read the IP configuration for each network
IPInterfaceProperties properties = network.GetIPProperties();
//discard those who do not have a real gateaway
if (properties.GatewayAddresses.Count > 0)
{
bool good = false;
foreach (GatewayIPAddressInformation gInfo in properties.GatewayAddresses)
{
//not a true gateaway (VmWare Lan)
if (!gInfo.Address.ToString().Equals("0.0.0.0"))
{
s[i] = gInfo.Address.ToString();
good = true;
break;
}
}
if (!good)
{
continue;
}
}
else
{
continue;
}
}
}
return s;
}
Related
I'm trying to post a (large) json file that's stored in the SPIFFS (LittleFS- of an arduino.
I first of all, fetch the JSON from a local IP address, which can change or is dynamic. Then, that json file gets stored in the internal flash of my ESP32 and sent over to our servers.
The goal is to have an ESP32 act as a bridge for local addresses.
For example:
Locally, there is a server running, that server is never accessible from outside of a network, but it is from within. We place an ESP32 in that network, to be able to read out data from the internal device and pass them through to our servers, for further processing.
The current code I have is the following;
HTTPClient http;
if (LittleFS.exists("/downloadedFile.json")) {
LittleFS.remove("/downloadedFile.json");
}
File f = LittleFS.open("/downloadedFile.json", "w", true);
if (f) {
String url;
// Build the URL...
if (username != "" && password != "") {
url = "http://" + username + ":" + password + "#" + ip + ":" + String(port) + "/data/file.json";
} else {
url = "http://" + ip + ":" + String(port) + "/data/file.json";
}
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
if (httpCode == HTTP_CODE_OK) {
http.writeToStream(&f);
}
} else {
// failed.
}
f.close();
} else {
// Unable to open file
}
http.end();
if (LittleFS.exists("/downloadedFile.json")) {
File f = LittleFS.open("/downloadedFile.json", "r");
if (f) {
WiFiClienSecure client;
client.setInsecure(); // test
if (!client.connect("my.somain.com", 443)) {
// failed to connect. (never gets in here)
return;
}
client.println("POST /path/to/my/endpoint HTTP/1.1");
client.println("Host: my.somain.com");
client.println("Content-Type: application/json");
client.println("Connection: keep-alive");
client.println("Content-Length: " + String(f.size()));
client.println();
// Build the body
int len = 0;
int total = 0;
uint8_t buf[1025] = {};
size_t _len = 256;
do {
len = f.read(buf, _len);
client.write(buf, len);
total += len;
} while (len > 0);
client.println(); // end line
client.stop();
f.close();
}
}
Downloading the file always works, except for sometimes random crashing the whole system. But that's the least of my concerns.
Locally I got it working to download and re-upload the file. Struggle is when I try to achieve the same result on the server (which uses https)
Only difference is this;
Server
Local
WiFiClienSecure client;
WiFiClient client;
client.setInsecure();
client.connect("my.somain.com", 443)
client.connect("IP", 80)
The main problem is that it doesn't work on the server and that it works really unstable. the file size (when I do f.size()) is 310831.
Any help and thoughts on getting this stable is appriciated!
how do i list all ip address in a machine using perl core modules only.
The code i have used is as follows. But it is listing only one ip address not all the ip addresses of a machine.
Can i be able to get list of ip addresses from a machine using perl.
I just want only ipv4 addresses.
To get all ip addresses should i use ifconfig command or is there a way perl can give me this with its API.
#!/usr/bin/perl -w
use Socket;
sub getIpAddressbyHost {
my ($hostname,$refAddress) = #_;
return -1 unless ($hostname ne "");
my $address = "";
unless ($hostname =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
eval {
if($hostname ne "") {
my $nformat = inet_aton($hostname);
unless(defined($nformat)) {
print("Error at getIpAddressbyHost for hostname $hostname\n");
return -1;
}
$address = inet_ntoa(inet_aton($hostname));
$$refAddress = $address;
}
};
if ($#) {
print("Error at getIpAddressbyHost for host $hostname : $#");
#$self->addErrorDetails("Error at getIpAddressbyHost for host $hostname : $#");
return -1;
}
}
else {
$$refAddress = $hostname;
}
return 1;
}
my $ipaddr = "Can't find";
print "enter the hostname: \n";
my $input = <STDIN>;
chomp($input);
my $retval = getIpAddressbyHost($input,\$ipaddr);
if($retval == 1){
print("the value of ipaddr: $ipaddr \n");
}
Why does the value of "Device Location" of the USB port change?
I use USBClassLibrary:
static List<string> UsbValues(string vid, string pid) {
var ListOfUSBDeviceProperties = new List<USBClass.DeviceProperties>();
var USBPort = new USBClass();
var list = new List<string>();
if(USBClass.GetUSBDevice(uint.Parse(vid, System.Globalization.NumberStyles.AllowHexSpecifier), uint.Parse(pid, System.Globalization.NumberStyles.AllowHexSpecifier), ref ListOfUSBDeviceProperties, false, null)) {
for (int i = 0; i < ListOfUSBDeviceProperties.Count; i++) {
list.Add(ListOfUSBDeviceProperties[i].DeviceLocation);
}
}
return list;
}
This returns: Port_#0002.Hub_#0009, but this value can suddenly change to another, for example Port_#0001.Hub_#0010.
Why is this happening? Maybe there's another way to bind a physical device?
I learned how to use ZeroMQ on a localhost, but I failed to do it on a remote IP.
Q1: Do I need a broker?If so,Q2: which broker and how to do it.?
Update:
OK. I'm using the ZMQ Weather Update example but with a remote IP ( not the localhost ). Here is what I do using C# ZMQ bindings ( however, I'm OK to use any other language ):
ZMQ Server:
using (var context = new ZContext())
using (var publisher = new ZSocket(context, ZSocketType.PUB))
{
string address = "tcp://*:5001";
publisher.Bind(address);
publisher.Send("msg")
}
Proxy:
using (var context = new ZContext())
using (var frontend = new ZSocket(context, ZSocketType.XSUB))
using (var backend = new ZSocket(context, ZSocketType.XPUB))
{
// Frontend is where the weather server sits
string localhost = "tcp://127.0.0.1:5001";
Console.WriteLine("I: Connecting to {0}", localhost);
frontend.Connect(localhost);
// Backend is our public endpoint for subscribers
string remoteIP = "216.123.23.98"; // For example
var tcpAddress = string.Format("tcp://{0}:8100", remoteIP); // I also tried localhost address here
Console.WriteLine("I: Binding on {0}", tcpAddress);
backend.Bind(tcpAddress);
var epgmAddress = string.Format("epgm://localhost;{0}:8100", remoteIP);
Console.WriteLine("I: Binding on {0}", epgmAddress);
backend.Bind(epgmAddress);
using (var subscription = ZFrame.Create(1))
{
subscription.Write(new byte[] { 0x1 }, 0, 1);
backend.Send(subscription);
}
// Run the proxy until the user interrupts us
ZContext.Proxy(frontend, backend);
}
Client:
using (var context = new ZContext())
using (var subscriber = new ZSocket(context, ZSocketType.SUB))
{
string remoteIP = "tcp://216.123.23.98"; //For example
Console.WriteLine("I: Connecting to {0}…", remoteIP);
subscriber.Connect(connect_to);
// Subscribe to zipcode
string zipCode = args[0];
Console.WriteLine("I: Subscribing to zip code {0}…", zipCode);
subscriber.Subscribe(zipCode);
// Process 10 updates
int i = 0;
long total_temperature = 0;
for (; i < 20; ++i)
{
ZError err;
using (var replyFrame = subscriber.ReceiveFrame(out err))
{
string reply = replyFrame.ReadString(Encoding.ASCII);
Console.WriteLine(reply);
total_temperature += Convert.ToInt64(reply.Split(' ')[1]);
}
}
Console.WriteLine("Average temperature for zipcode '{0}' was {1}", zipCode, (total_temperature / i));
}
When I run this I get error in Server and error in proxy - server gets
Invalid end point
and proxy gets EINVAL(22):
Invalid argument at ZeroMQ.ZSocket.Bind(String endpoint)
A1: No, ZeroMQ is a Broker-less messaging framework.
A2: N/A
How to repair the code?
All the services need to obey respective transport-class addressing rules, for the TCP/IP case - both the .bind() / .connect() methods have to state both parts of the IP:PORT# specification ( with some aids from DNS-resolution for the IP-part, but the :PORT#-part is still mandatory )
( which the source-code does not meet in client, ref.:
subscriber.Connect(connect_to);
whereas there ought be also a Proxy-side matching :PORT#, i.e.:8100, specified, for a correct .connect() ).
For the clarity and for avoiding a port#-collision, remove the epgm transport class from the code.
I successfully installed Redis on two machines and made then work as Master-Slave.
I tested some code to check if replication work and everything is ok.
My client manager looks like
var manager = new PooledRedisClientManager(new[] { "MasterIP:6379" }, new[] { "MasterIP:6379", "SlaveIP:6379" });
But now i shutdown my master instance and when i test my code again i get an error like client cant connect to Master server.
p.s For read i use GetReadOnlyCacheClient();
I repeated my code and i notice that client first is getting Master (error cant connect), then when i run my code again client is getting Slave, then again when i run my code client is getting master and so on.
I downloaded source code on ServiceStack.Redis client. I just wanted to check when that error happens and here is the code.
private void Connect()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
{
SendTimeout = SendTimeout,
ReceiveTimeout = ReceiveTimeout
};
try
{
if (ConnectTimeout == 0)
{
socket.Connect(Host, Port);
}
else
{
var connectResult = socket.BeginConnect(Host, Port, null, null);
connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
}
if (!socket.Connected)
{
socket.Close();
socket = null;
return;
}
Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);
if (Password != null)
SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
db = 0;
var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
lastCommand = null;
lastSocketException = null;
LastConnectedAtTimestamp = Stopwatch.GetTimestamp();
if (ConnectionFilter != null)
{
ConnectionFilter(this);
}
}
catch (SocketException ex)
{
if (socket != null)
socket.Close();
socket = null;
HadExceptions = true;
var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
log.Error(throwEx.Message, ex);
throw throwEx;
}
}
I really dont understand this code, couze project is really big, but i think there is no If this server fails, then try to get from another host in read only server list if any other exist
I can make some kind of mine custom logic to check if fail to try to get another read only instance..but isnt this client supported to be ready about this issue?