This is the code I have:
/*
* This is a C# Program which displays the URL of an input IP address.
*/
using System;
using System.Net;
namespace CNT4704L
{
class MySocketLab
{
static void Main()
{
Console.Write("Enter an IP address (e.g., 131.247.2.211): ");
IPAddress addr = Console.ReadLine();
string strSiteName = Dns.GetHostEntry(addr);
Console.Write("\nHost name of ", addr);
Console.Write(" is ", strSiteName);
}
}
}
It says I can't implicitly convert type string to System.Net.IPAddress, but I'm not sure what the Url I'm trying to get could be other than a string.
Your problem is on this line:
IPAddress addr = Console.ReadLine();
The Console.ReadLine function returns a string not a IPAddress.
Just change it to:
var addr = Console.ReadLine();
Related
Hello I have a question i'm trying to get all ip addresses of an nslookup domain. I'm using the following script in c# on a button but it only prints out 1 ip address, what am I doing wrong?
string myHost = "domain.com";
string myIP = null;
for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
{
//myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
txtIp.Text = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
}
}
All help would be greatfull because I've seen mutiple answers here on stackoverflow but I can't get one to work properly.
regards,
Dennis
First of all, you should avoid making the dns request 3 times. Store the result in a variable.
Second, you set txtIp.Text to the last entry. You need to append the strings, but you replace them. Try this code:
string myHost = "domain.com";
string myIP = null;
IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(myHost);
for (int i = 0; i <= hostEntry.AddressList.Length - 1; i++)
{
if (!hostEntry.AddressList[i].IsIPv6LinkLocal)
{
txtIp.Text += hostEntry.AddressList[i].ToString();
}
}
But this can still be shortened to this:
string myHost = "domain.com";
string myIP = null;
IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(myHost);
txtIP.Text = string.Join(", ", hostEntry.AddressList.Where(ip => !ip.IsIPv6LinkLocal).Select(ip => ip.ToString()));
This gives you a comma-separated list of the ip addresses.
I'm trying to remove all CRLF characters from the string dataFromClient in the C# code bellow. All of the following attempts have failed so far and I'd be very thankful for your help:
edit:
The problem is that whenever the Console.WriteLine(dataFromClient) method is called, the string prints but looks like this: "\vposition?:X\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0....." I want the output to only be "position?:X". But have not been able to trim the "\0" from the string.
This code is my first attempt at setting up a simple server to accept a connection form a third party software. Requests are made from the client, then this server parses the request to commands that a motorized Cartesian stage understands.
Bellow is the code from the server portion/ class of the console app.
Posts with suggestions I already tried:
Removing carriage return and new-line from the end of a string in c#
Serial communication and CRLF C#
How to WriteAllLines in C# without CRLF
Remove a character from a string
String Trim Spaces doesn't work
Here is the code:
using System;
using System.Net;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace autotile_V001
{
public class Myserver
{
int MyServerPort;
bool go = true;
int requestCount = 0;
string dataFromClient;
string serverResponse;
IPAddress ipAddr = IPAddress.Loopback;
public string process(string s)
{
int len = s.Length;
int current = 0;
StringBuilder sb = new StringBuilder(len);
while (current < len - 1)
{
if ((s[current] == ' ' && s[current + 1] == ' '))
{
break;
}
else
{
sb.Append(s[current]);
}
current++;
}
return sb.ToString();
}
public void StartMyServer()
{
TcpListener serverSocket = new TcpListener(ipAddr, MyServerPort);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accepted connection from client");
requestCount = 0;
while ((go))
{
try
{
requestCount++;
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[(int)clientSocket.ReceiveBufferSize];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
Console.WriteLine(" >> Data from client - {0}", (String.Join("\n", dataFromClient)).Trim());
serverResponse = Console.ReadLine();
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
go = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
go = false;
}
}
}
public Myserver(int someData)
{
MyServerPort = someData;
}
}
}
Trim() just removes leading and trailing whitespace - not whitespace within a string.
You'll need to use Replace to remove out unwanted characters or strings from inside a string. In the case above, any trialing non-white space character (which might not be visible, e.g. 0x0) in the byte stream will cause the call to Trim not to work.
var someString = "FOO\r\n\r\n\0";
var strippedTrim = someString.Trim(); // Fail - "FOO\r\n\r\n\0"
var strippedReplace = someString.Replace("\r\n", ""); // "FOO\0"
// .Replace() any other unwanted white space, e.g. "\t"
Noted however that Trim() will still remove a trailing naked '\n' (as opposed to Windows CRLF), so it isn't the String.Join("\n" causing the bug.
Edit
Just to clarify the string.Join - string.Join when used on a single string is redundant / has no effect (neither does it treat the string as an array of single character strings).
var join = string.Join("x", "FOO\r\n\r\n").Trim(); // Works - "FOO"
So I'm working on a little side project in c# and want to read a long text file and when it encounters the line "X-Originating-IP: [192.168.1.1]" I would like to grab the IP and display to console just the recognized IP #, so just 192.168.1.1 etc. I am having trouble understanding regex. Anyone who could get me started is much appreciated. What I have so far is below.
namespace x.Originating.Ip
{
class Program
{
static void Main(string[] args)
{
int counter = 0;
string line;
System.IO.StreamReader file =
new System.IO.StreamReader("C:\\example.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("X-Originating-IP: "))
Console.WriteLine(line);
counter++;
}
file.Close();
Console.ReadLine();
}
}
}
Try this example:
//Add this namespace
using System.Text.RegularExpressions;
String input = #"X-Originating-IP: [192.168.1.1]";
Regex IPAd = new Regex(#"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
MatchCollection MatchResult = IPAd.Matches(input);
Console.WriteLine(MatchResult[0]);
You don't need to use regular expression:
if (line.Contains("X-Originating-IP: ")) {
string ip = line.Split(':')[1].Trim(new char[] {'[', ']', ' '});
Console.WriteLine(ip);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Net.WebClient webclient = new System.Net.WebClient();
string ip = webclient.DownloadString("http://whatismyip.org/");
Regex reg = new Regex("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
if (reg.Match(ip).Success)
{
Console.WriteLine(reg.Match(ip).ToString ());
Console.WriteLine("Success");
}
// Console.Write (ip);
Console.ReadLine();
}
}
}
I'm not sure but I suppose your text file contains one IP address each row, now your codes can be simplified like this below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace x.Originating.Ip
{
class Program
{
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines("Your path & filename.extension");
Regex reg = new Regex("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
for (int i = 0; i < lines.Length; ++i)
{
if (reg.Match(lines[i]).Success)
{
//Do what you want........
}
}
}
}
}
The following regular expression should get you what you want:
(?<=X-Originating-IP: +)((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)
This uses a positive lookbehind to assert that "X-Originating-IP: " exists followed by an IPv4 address. Only the IP address will be captured by the match.
Rather than doing a regex, it looks like you are parsing a MIME email, consider LumiSoft.Net.MIME which lets you access the headers with a defined API.
Alternatively, use the built in IPAddress.Parse class, which supports both IPv4 and IPv6:
const string x_orig_ip = "X-Originating-IP:";
string header = "X-Originating-IP: [10.24.36.17]";
header = header.Trim();
if (header.StartsWith(x_orig_ip, StringComparison.OrdinalIgnoreCase))
{
string sIpAddress = header.Substring(x_orig_ip.Length, header.Length - x_orig_ip.Length)
.Trim(new char[] { ' ', '\t', '[', ']' });
var ipAddress = System.Net.IPAddress.Parse(sIpAddress);
// do something with IP address.
return ipAddress.ToString();
}
I am really unfamiliar with C#, it's been years since I've programmed with this language. I'm going to post the code I have, which has build errors. This is what I'm trying to do, but I really am not sure how to proceed. I have hit a wall and really have no clue how to proceed:
Enter an address (as a string)
Resolve the address using the appropriate function
Print out the complete host information
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace CSDNS
{
class Program
{
static void PrintHostInfo(String host)
{
{
IPHostEntry hostinfo;
try
{
hostinfo = Dns.GetHostEntry("www.sunybroome.edu"); // DNS Name Resolution
//
// The IP address is now in hostinfo structure
// Print out the contents of hostinfo structure
// in an easily readable form with labels. For
// example, the host name can be output using:
Console.WriteLine("Hostname = {0}\n", hostinfo.HostName);
}
catch
{
// Print out the exception here...
}
try
{
IPHostEntry hostInfo;
//Attempt to resolve DNS for given host or address
hostInfo = Dns.Resolve(host);
//Display the primary host name
Console.WriteLine("\tCanonical Name: " + hostInfo.HostName);
//Display list of IP addresses for this host
Console.Write("\tIP Addresses: ");
foreach (IPAddress ipaddr in hostInfo.AddressList)
{
Console.Write(ipaddr.ToString() + " ");
}
Console.WriteLine();
//Display list of alias names for this host
Console.Write("\tAliases: ");
foreach (String alias in hostInfo.Aliases)
{
Console.Write(alias + " ");
}
Console.WriteLine("\n");
}
catch (Exception)
{
Console.WriteLine("\tUnable to resolve host: " + host + "\n");
}
}
}
static void Main(string[] args)
{
//Get and print local host info
try
{
Console.WriteLine("Local Host:");
String localHostName = Dns.GetHostName();
Console.WriteLine("\tHost Name: " + localHostName);
PrintHostInfo(localHostName);
}
catch (Exception)
{
Console.WriteLine("Unable to resolve local host\n");
}
//Get and print info for hosts given on command line
foreach (String arg in args)
{
Console.WriteLine(arg + ":");
PrintHostInfo(arg);
}
}
}
}
You need to pass in host to the Resolve method, not hostInfo (i.e. the string that contains the host you want to resolve):
hostInfo = Dns.Resolve(host);
How can I get the computer name and IP address of my PC programmatically? For example, I want to display that information in a text box.
Have a look at this: link
and this: link
textBox1.Text = "Computer Name: " + Environment.MachineName
textBox2.Text = "IP Add: " + Dns.GetHostAddresses(Environment.MachineName)[0].ToString();
Check more about this : How To Get IP Address Of A Machine
System.Security.Principal.WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
string strName = p.Identity.Name;
To get the machine name,
System.Environment.MachineName
or
using System.Net;
strHostName = DNS.GetHostName ();
// Then using host name, get the IP address list..
IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
IPAddress [] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
}
In easy way..
string IP_Address = Dns.GetHostByName(Environment.MachineName).AddressList[0].toString();
I use the following found at: https://stackoverflow.com/a/27376368/2510099
for the IP address
public string GetIPAddress()
{
string ipAddress = null;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530); //Google public DNS and port
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
ipAddress = endPoint.Address.ToString();
}
return ipAddress;
}
and for the machine name
Environment.MachineName;