I am looking for solution that can proxy my udp packets. I have one client sending udp packets to a server. Connection between them is very bad and I get lot of packet loss. One solution is to have a new proxy server that will just redirect all packets from client to destination server. The new proxy server has good connection to both locations.
So far I have found Simple UDP proxy/pipe
Are there some tools for such purpose ?
Cheers
I also wrote a Python script for this one day. This one goes both ways:
https://github.com/EtiennePerot/misc-scripts/blob/master/udp-relay.py
Usage: udp-relay.py localPort:remoteHost:remotePort
Then, point your UDP application to localhost:localPort and all packets will bounce to remoteHost:remotePort.
All packets sent back from remoteHost:remotePort will be bounced back to the application, assuming it is listening on the port it just sent packets from.
Here is Python code written for this purpose:
import socket
from threading import Thread
class Proxy(Thread):
""" used to proxy single udp connection
"""
BUFFER_SIZE = 4096
def __init__(self, listening_address, forward_address):
print " Server started on", listening_address
Thread.__init__(self)
self.bind = listening_address
self.target = forward_address
def run(self):
# listen for incoming connections:
target = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
target.connect(self.target)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.bind(self.bind)
except socket.error, err:
print "Couldn't bind server on %r" % (self.bind, )
raise SystemExit
while 1:
datagram = s.recv(self.BUFFER_SIZE)
if not datagram:
break
length = len(datagram)
sent = target.send(datagram)
if length != sent:
print 'cannot send to %r, %r !+ %r' % (self.target, length, sent)
s.close()
if __name__ == "__main__":
LISTEN = ("0.0.0.0", 8008)
TARGET = ("localhost", 5084)
while 1:
proxy = Proxy(LISTEN, TARGET)
proxy.start()
proxy.join()
print ' [restarting] '
I used this two scripts to test it.
import socket
target = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
target.connect(("localhost", 8008))
print 'sending:', target.send("test data: 123456789")
and
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("localhost", 5084))
while 1:
datagram = s.recv(1024)
if not datagram:
break
print repr(datagram)
s.close()
This version sends one reply back. It's good for one client only.
import socket
from threading import Thread
class Proxy(Thread):
""" used to proxy single udp connection
"""
BUFFER_SIZE = 4096
def __init__(self, listening_address, forward_address):
print " Server started on", listening_address
Thread.__init__(self)
self.bind = listening_address
self.target = forward_address
def run(self):
# listen for incoming connections:
target = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
target.connect(self.target)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.bind(self.bind)
except socket.error, err:
print "Couldn't bind server on %r" % (self.bind, )
raise SystemExit
while 1:
(datagram,addr) = s.recvfrom(self.BUFFER_SIZE)
if not datagram:
break
length = len(datagram)
sent = target.send(datagram)
if length != sent:
print 'cannot send to %r, %r !+ %r' % (self.s, length, sent)
datagram = target.recv(self.BUFFER_SIZE)
if not datagram:
break
length = len(datagram)
sent = s.sendto(datagram,addr)
if length != sent:
print 'cannot send to %r, %r !+ %r' % (self.s, length, sent)
s.close()
if __name__ == "__main__":
LISTEN = ("0.0.0.0", 5093)
TARGET = ("10.12.2.26", 5093)
while 1:
proxy = Proxy(LISTEN, TARGET)
proxy.start()
proxy.join()
print ' [restarting] '
Here is a working
TCP or UDP Redirector / UDP Proxy / UDP Pipe / TCP Proxy / TCP Pipe
I created many different models of UDP Proxy connection bouncers and they all seem to lose connection using the standard Sockets class, but using UDPClient classes this problem completely went away.
The UDP Proxy is only 25 lines of code but the power and stability is off the charts
Below is examples how to do it in both TCP and UDP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;
using System.Net;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string Address= "*PUT IP ADDRESS HERE WHERE UDP SERVER IS*";
int UDPPort = *PUT UDP SERVER PORT HERE*;
UdpRedirect _UdpRedirect = new UdpRedirect() { _address = Address, _Port = UDPPort};
Thread _Thread = new Thread(_UdpRedirect.Connect);
_Thread.Name = "UDP";
_Thread.Start();
int TCPPort = *PUT TCP PORT HERE FOR TCP PROXY*;
TcpRedirect _TcpRedirect = new TcpRedirect(Address, TCPPort);
}
}
class UdpRedirect
{
public string _address;
public int _Port;
public UdpRedirect()
{
}
public void Connect()
{
UdpClient _UdpClient = new UdpClient(_Port);
int? LocalPort = null;
while (true)
{
IPEndPoint _IPEndPoint = null;
byte[] _bytes = _UdpClient.Receive(ref _IPEndPoint);
if (LocalPort == null) LocalPort = _IPEndPoint.Port;
bool Local = IPAddress.IsLoopback(_IPEndPoint.Address);
string AddressToSend = null;
int PortToSend = 0;
if (Local)
{
AddressToSend = _address;
PortToSend = _Port;
}
else
{
AddressToSend = "127.0.0.1";
PortToSend = LocalPort.Value;
}
_UdpClient.Send(_bytes, _bytes.Length, AddressToSend, PortToSend);
}
}
}
class TcpRedirect
{
public TcpRedirect(string _address, int _Port)
{
TcpListener _TcpListener = new TcpListener(IPAddress.Any, _Port);
_TcpListener.Start();
int i = 0;
while (true)
{
i++;
TcpClient _LocalSocket = _TcpListener.AcceptTcpClient();
NetworkStream _NetworkStreamLocal = _LocalSocket.GetStream();
TcpClient _RemoteSocket = new TcpClient(_address, _Port);
NetworkStream _NetworkStreamRemote = _RemoteSocket.GetStream();
Console.WriteLine("\n<<<<<<<<<connected>>>>>>>>>>>>>");
Client _RemoteClient = new Client("remote" + i)
{
_SendingNetworkStream = _NetworkStreamLocal,
_ListenNetworkStream = _NetworkStreamRemote,
_ListenSocket = _RemoteSocket
};
Client _LocalClient = new Client("local" + i)
{
_SendingNetworkStream = _NetworkStreamRemote,
_ListenNetworkStream = _NetworkStreamLocal,
_ListenSocket = _LocalSocket
};
}
}
public class Client
{
public TcpClient _ListenSocket;
public NetworkStream _SendingNetworkStream;
public NetworkStream _ListenNetworkStream;
Thread _Thread;
public Client(string Name)
{
_Thread = new Thread(new ThreadStart(ThreadStartHander));
_Thread.Name = Name;
_Thread.Start();
}
public void ThreadStartHander()
{
Byte[] data = new byte[99999];
while (true)
{
if (_ListenSocket.Available > 0)
{
int _bytesReaded = _ListenNetworkStream.Read(data, 0, _ListenSocket.Available);
_SendingNetworkStream.Write(data, 0, _bytesReaded);
Console.WriteLine("(((((((" + _bytesReaded + "))))))))))" + _Thread.Name + "\n" + ASCIIEncoding.ASCII.GetString(data, 0, _bytesReaded).Replace((char)7, '?'));
}
Thread.Sleep(10);
}
}
}
}
}
Related
When I tried using Ocelot as a WebSocket proxy, I could not get it working for wss. I was able to see it working for ws.
When we are trying to proxy for wss getting decrypt operation failed while reading the bytes at the server side socket. With plan ws I am able to get this working.
Ocelot config as follows, where wss proxying is specified:
{
"Routes": [
{
"DownstreamPathTemplate": "/ws",
"UpstreamPathTemplate": "/{anything}",
"DownstreamScheme": "wss",
"DownstreamHostAndPorts": [
{
"Host": "127.0.0.1",
"Port": 8080
}
]
}
]
}
Websocket Server code which listens on port 8080:
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
class Server
{
public static void Main()
{
string ip = "127.0.0.1";
int port = 8080;
var server = new TcpListener(IPAddress.Parse(ip), port);
server.Start();
Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection...", ip, port);
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");
byte[] pfxData = File.ReadAllBytes(#"C:\Users\e409316\Desktop\test.pfx");
var cert = new X509Certificate2(pfxData, "Password1", X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.Exportable);
Stream sourceTcpStream = new SslStream(client.GetStream(), false);
(sourceTcpStream as SslStream).AuthenticateAsServer(
cert,
false,
SslProtocols.Tls12, true);
Stream stream = sourceTcpStream;//client.GetStream();
//Stream stream = client.GetStream();
// enter to an infinite cycle to be able to handle every change in stream
while (true)
{
//while (!stream.DataAvailable) ;
while (client.Available < 3) ; // match against "get"
byte[] bytes = new byte[client.Available];
stream.Read(bytes, 0, client.Available);
string s = Encoding.UTF8.GetString(bytes);
if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase))
{
Console.WriteLine("=====Handshaking from client=====\n{0}", s);
// 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
// 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
// 3. Compute SHA-1 and Base64 hash of the new value
// 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);
// HTTP/1.1 defines the sequence CR LF as the end-of-line marker
byte[] response = Encoding.UTF8.GetBytes(
"HTTP/1.1 101 Switching Protocols\r\n" +
"Connection: Upgrade\r\n" +
"Upgrade: websocket\r\n" +
"Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");
stream.Write(response, 0, response.Length);
}
else
{
bool fin = (bytes[0] & 0b10000000) != 0,
mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
int opcode = bytes[0] & 0b00001111, // expecting 1 - text message
msglen = bytes[1] - 128, // & 0111 1111
offset = 2;
if (msglen == 126)
{
// was ToUInt16(bytes, offset) but the result is incorrect
msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
offset = 4;
}
else if (msglen == 127)
{
Console.WriteLine("TODO: msglen == 127, needs qword to store msglen");
// i don't really know the byte order, please edit this
// msglen = BitConverter.ToUInt64(new byte[] { bytes[5], bytes[4], bytes[3], bytes[2], bytes[9], bytes[8], bytes[7], bytes[6] }, 0);
// offset = 10;
}
if (msglen == 0)
Console.WriteLine("msglen == 0");
else if (mask)
{
byte[] decoded = new byte[msglen];
byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
offset += 4;
for (int i = 0; i < msglen; ++i)
decoded[i] = (byte)(bytes[offset + i] ^ masks[i % 4]);
string text = Encoding.UTF8.GetString(decoded);
Console.WriteLine("{0}", text);
}
else
Console.WriteLine("mask bit not set");
Console.WriteLine();
}
}
}
}
Websocket Client code which tries to connect to ocelot endpoint (upstream endpoint on port 5000):
ClientWebSocket client = new ClientWebSocket();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
client.ConnectAsync(new Uri("wss://127.0.0.1:5000/"), CancellationToken.None).Wait();
var buffer = new byte[]{1,2,3};
client.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true,CancellationToken.None);
Error: The decryption operation failed
Found it to be a certificate validity issue. Solved it by using a trusted certificate.
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 have a question about custom receiver of spark streaming.
I code a copy like the following :
import java.io.{BufferedReader, InputStreamReader}
import java.net.Socket
import java.nio.charset.StandardCharsets
import org.apache.spark.SparkConf
import org.apache.spark.Logging
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.receiver.Receiver
/**
* Custom Receiver that receives data over a socket. Received bytes is interpreted as
* text and \n delimited lines are considered as records. They are then counted and printed.
*
* To run this on your local machine, you need to first run a Netcat server
* `$ nc -lk 9999`
* and then run the example
* `$ bin/run-example org.apache.spark.examples.streaming.CustomReceiver localhost 9999`
*/
object CustomReceiver2 {
def main(args: Array[String]) {
// Create the context with a 1 second batch size
val sparkConf = new SparkConf().setAppName("CustomReceiver")
val ssc = new StreamingContext(sparkConf, Seconds(1))
// Create a input stream with the custom receiver on target ip:port and count the
// words in input stream of \n delimited text (eg. generated by 'nc')
val lines = ssc.receiverStream(new CustomReceiver2("192.168.1.0", 11.toInt))
lines.saveAsObjectFiles("hdfs:/tmp/customreceiver/")
ssc.start()
ssc.awaitTermination()
}
}
class CustomReceiver2(host: String, port: Int)
extends Receiver[String](StorageLevel.MEMORY_AND_DISK_2) with Logging {
def onStart() {
// Start the thread that receives data over a connection
new Thread("Socket Receiver") {
override def run() { receive() }
}.start()
}
def onStop() {
}
/** Create a socket connection and receive data until receiver is stopped */
private def receive() {
var socket: Socket = null
var userInput: String = null
try {
logInfo("Connecting to " + host + ":" + port)
socket = new Socket(host, port)
logInfo("Connected to " + host + ":" + port)
val reader = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))
userInput = reader.readLine()
while(!isStopped && userInput != null) {
println("userInput= "+userInput)
store(userInput)
userInput = reader.readLine()
println("==store data finished==")
}
reader.close()
socket.close()
logInfo("Stopped receiving")
restart("Trying to connect again")
} catch {
case e: java.net.ConnectException =>
restart("Error connecting to " + host + ":" + port, e)
case t: Throwable =>
restart("Error receiving data", t)
}
}
}
It passes the compiler and runs smoothly. I did not take the output as i expected, because the hdfs file was empty all the time.
Could anyone give me a hand ?
I tried to make an example of simple socket server.
Build and run successfully. However it doesn't work well.
Client couldn't connect to this server.
How to solve this problem? I need your help, thanks.
import Foundation
let BUFF_SIZE = 1024
func initStruct<S>() -> S {
let struct_pointer = UnsafePointer<S>.alloc(1)
let struct_memory = struct_pointer.memory
struct_pointer.destroy()
return struct_memory
}
func sockaddr_cast(p: ConstUnsafePointer<sockaddr_in>) -> UnsafePointer<sockaddr> {
return UnsafePointer<sockaddr>(p)
}
func socklen_t_cast(p: UnsafePointer<Int>) -> UnsafePointer<socklen_t> {
return UnsafePointer<socklen_t>(p)
}
var server_socket: Int32
var client_socket: Int32
var server_addr_size: Int
var client_addr_size: Int
var server_addr: sockaddr_in = initStruct()
var client_addr: sockaddr_in = initStruct()
var buff_rcv: Array<CChar> = []
var buff_snd: String
server_socket = socket(PF_INET, SOCK_STREAM, 0);
if server_socket == -1
{
println("[Fail] Create Server Socket")
exit(1)
}
else
{
println("[Success] Created Server Socket")
}
server_addr_size = sizeof(server_addr.dynamicType)
memset(&server_addr, 0, UInt(server_addr_size));
server_addr.sin_family = sa_family_t(AF_INET)
server_addr.sin_port = 4000
server_addr.sin_addr.s_addr = UInt32(0x00000000) // INADDR_ANY = (u_int32_t)0x00000000 ----- <netinet/in.h>
let bind_server = bind(server_socket, sockaddr_cast(&server_addr), socklen_t(server_addr_size))
if bind_server == -1
{
println("[Fail] Bind Port");
exit(1);
}
else
{
println("[Success] Binded Port");
}
if listen(server_socket, 5) == -1
{
println("[Fail] Listen");
exit(1);
}
else
{
println("[Success] Listening : \(server_addr.sin_port) Port ...");
}
var n = 0
while n < 1
{
client_addr_size = sizeof(client_addr.dynamicType)
client_socket = accept(server_socket, sockaddr_cast(&client_addr), socklen_t_cast(&client_addr_size))
if client_socket == -1
{
println("[Fail] Accept Client Connection");
exit(1);
}
else
{
println("[Success] Accepted Client : \(inet_ntoa(client_addr.sin_addr)) : \(client_addr.sin_port)");
}
read(client_socket, &buff_rcv, UInt(BUFF_SIZE))
println("[Success] Received : \(buff_rcv)")
buff_snd = "\(strlen(buff_rcv)) : \(buff_rcv)"
write(client_socket, &buff_snd, strlen(buff_snd) + 1)
close(client_socket)
}
The port number in the socket address must be in big-endian byte order:
server_addr.sin_port = UInt16(4000).bigEndian
So your program actually listens on port 40975 (hex 0xA00F) and not
on port 4000 (hex 0x0FA0).
Another problem is here:
var buff_rcv: Array<CChar> = []
// ...
read(client_socket, &buff_rcv, UInt(BUFF_SIZE))
Your buffer is an empty array, but recv() expects a buffer of size BUFF_SIZE.
The behaviour is undefined. To get a buffer of the required size, use
var buff_rcv = [CChar](count:BUFF_SIZE, repeatedValue:0)
// ...
read(client_socket, &buff_rcv, UInt(buff_rcv.count))
Remark: Here you cast the address of an Int to the address of an socklen_t
and pass that to the accept() function:
client_socket = accept(server_socket, sockaddr_cast(&client_addr), socklen_t_cast(&client_addr_size))
That is not safe. If Int and socklen_t have different sizes then the behaviour
will be undefined. You should declare server_addr_size and client_addr_size
as socklen_t and remove the socklen_t_cast() function:
client_socket = accept(server_socket, sockaddr_cast(&client_addr), &client_addr_size)
As Martin R commented before, the write command shouldn't be using the swift string as that. Something like this will work properly:
write(client_socket, buff_snd.cStringUsingEncoding(NSUTF8StringEncoding)!, countElements(buff_snd) + 1)
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;
}