SEO: A whois server that work for .SE domains? - c#

I'm developing a small domain checker and I can't get .SE to work:
public string Lookup(string domain, RecordType recordType, SeoToolsSettings.Tld tld)
{
TcpClient tcp = new TcpClient();
tcp.Connect(tld.WhoIsServer, 43);
string strDomain = recordType.ToString() + " " + domain + "\r\n";
byte[] bytDomain = Encoding.ASCII.GetBytes(strDomain.ToCharArray());
Stream s = tcp.GetStream();
s.Write(bytDomain, 0, strDomain.Length);
StreamReader sr = new StreamReader(tcp.GetStream(), Encoding.ASCII);
string strLine = "";
StringBuilder builder = new StringBuilder();
while (null != (strLine = sr.ReadLine()))
{
builder.AppendLine(strLine);
}
tcp.Close();
if (tld.WhoIsDelayMs > 0) System.Threading.Thread.Sleep(tld.WhoIsDelayMs);
return builder.ToString();
}
I've tried whois servers whois.nic-se.se and whois.iis.se put I keep getting:
# Copyright (c) 1997- .SE (The Internet Infrastructure Foundation).
# All rights reserved.
# The information obtained through searches, or otherwise, is protected
# by the Swedish Copyright Act (1960:729) and international conventions.
# It is also subject to database protection according to the Swedish
# Copyright Act.
# Any use of this material to target advertising or
# similar activities is forbidden and will be prosecuted.
# If any of the information below is transferred to a third
# party, it must be done in its entirety. This server must
# not be used as a backend for a search engine.
# Result of search for registered domain names under
# the .SE top level domain.
# The data is in the UTF-8 character set and the result is
# printed with eight bits.
"domain google.se" not found.
Edit:
I've tried changing to UTF8 with no other result.
When I try using whois from sysinternals I get the correct result, but not with my code, not even using SE.whois-servers.net.
/Niels

Hmmm, when doing a whois google.se on my Mac I get the following:
# Copyright (c) 1997- .SE (The Internet Infrastructure Foundation).
# All rights reserved.
# The information obtained through searches, or otherwise, is protected
# by the Swedish Copyright Act (1960:729) and international conventions.
# It is also subject to database protection according to the Swedish
# Copyright Act.
# Any use of this material to target advertising or
# similar activities is forbidden and will be prosecuted.
# If any of the information below is transferred to a third
# party, it must be done in its entirety. This server must
# not be used as a backend for a search engine.
# Result of search for registered domain names under
# the .SE top level domain.
# The data is in the UTF-8 character set and the result is
# printed with eight bits.
state: active
domain: google.se
holder: googoo5855-00001
admin-c: -
tech-c: -
billing-c: -
created: 2008-10-20
modified: 2010-09-18
expires: 2011-10-20
transferred: 2009-03-06
nserver: ns1.google.com
nserver: ns2.google.com
nserver: ns3.google.com
nserver: ns4.google.com
dnssec: unsigned delegation
status: ok
registrar: MarkMonitor Inc
So it's probably just your code. Maybe you have to do the request in a non-ASCII encoding, such as UTF8?

I finally solved it.
Using wireshark, I saw that the whois from sysinternals doesn't add the "DOMAIN" part:
string strDomain = recordType.ToString() + " " + domain + "\r\n";
(recordType.ToString == "DOMAIN").
So when I removed that, it worked!

without looking to your code why not:
example # http://balexandre.com/verifyDomain.aspx
this will give you, for par.se
IP Found:
- 193.13.249.142
Host name:
- parweb1.par.se
Aliases:
none
IP address list:
- 193.13.249.142
If you just want the RIPE information of an IP, you can also use my page for test
http://balexandre.com/iplookup.aspx?ip={ip to test}
Button event
protected void btnCheck_Click(object sender, EventArgs e)
{
DomainCheck domain = new DomainCheck();
string ip = domain.GetIPFromDomain(txtDomain.Text.Trim());
litResponse.Text = String.Format(
"IP{0} Found:<br/> - <strong>{1}</strong><br/>{2}",
ip.Contains(",") ? "'s" : "",
ip.Replace(",", "<br/> - "), domain.VerifyIP(ip));
}
DomainCheck code:
public class DomainCheck
{
public DomainCheck() { }
public string VerifyIP(string ipAddress)
{
if (String.IsNullOrEmpty(ipAddress))
return "IP Address is invalid!";
string r = "";
if (ipAddress.Contains(","))
{
foreach (string ip in ipAddress.Split(','))
r += String.Format("<br/><br/>#### <em>Checking {0}</em>{1}", ip, CheckIPAddress(ip));
}
else
r += CheckIPAddress(ipAddress);
return r;
}
public string GetIPFromDomain(string hostname)
{
string r = "";
IPAddress[] addresslist = Dns.GetHostAddresses(hostname);
foreach (IPAddress theaddress in addresslist)
{
r += String.Format("{0},", theaddress.ToString());
}
return String.IsNullOrEmpty(r) ? null : r.TrimEnd(',');
}
private string CheckIPAddress(string ipAddress)
{
string r = "";
try
{
IPAddress hostIPAddress = IPAddress.Parse(ipAddress);
IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress);
// Get the IP address list that resolves to the host names contained in
// the Alias property.
IPAddress[] address = hostInfo.AddressList;
// Get the alias names of the addresses in the IP address list.
String[] alias = hostInfo.Aliases;
r += String.Format(
"<br/>Host name: <br/>- <strong>{0}</strong><br/>Aliases: ",
hostInfo.HostName);
if (alias.Length == 0)
r += "<br/><em>none</em>";
else
for (int index = 0; index < alias.Length; index++)
r += String.Format("<br/>- <strong>{0}</strong>", alias[index]);
r += "<br/>IP address list: ";
if (address.Length == 0)
r += "<br/><em>none</em>";
else
for (int index = 0; index < address.Length; index++)
r += String.Format("<br/>- <strong>{0}</strong>", address[index]);
}
catch (SocketException e)
{
r = String.Format(
"SocketException caught!!!<br/>Source : {0}<br/>Message : {1}",
e.Source, e.Message);
}
catch (FormatException e)
{
r = String.Format(
"FormatException caught!!!<br/>Source : {0}<br/>Message : {1}",
e.Source, e.Message);
}
catch (ArgumentNullException e)
{
r = String.Format(
"ArgumentNullException caught!!!<br/>Source : {0}<br/>Message : {1}",
e.Source, e.Message);
}
catch (Exception e)
{
r = String.Format(
"Exception caught!!!<br/>Source : {0}<br/>Message : {1}",
e.Source, e.Message);
}
return r;
}
}

Related

Fetch particular string from particular block

I am new to c#. I have text file with data in it but I want to read particular block line data.
Here address can occur multiple times in text file.
Something here...
... ... ...
interface "system"
address 10.4.1.10/32
no shutdown
exit
something here...
... ... ...
address 101.4.1.11/32
but i want to capture within this
interface "system"
address 10.4.1.10/32
no shutdown
exit
I want to capture this ip from the block:
10.4.1.10
I tried this code:
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();
Expected Output:
my expected output is to capture the ip address from that block ie.10.4.1.10
that ip is inside "interface system" block.. that makes that address as unique.. as there can be many ips with keyword address. So i want to take address which is inside interface system block.
Please let me know how i can capture particular string from the block.
Regular Expressions are perfectly suited to handle this type of "problem". The following console app demonstrates how to use Regex to extract the desired IP address from the targeted string block.
private static readonly string IPV4_PATTERN = "[0-9./]";
private static readonly string IPV4_IPV6_PATTERN = "[A-Z0-9:./]";
static void Main(string[] args)
{
TestSearchFile();
}
private static string ParseIpWithRegex(string textToSearch, string startBlock, string endBlock)
{
var pattern = $#"{startBlock}\D*\s*({IPV4_IPV6_PATTERN}+).*{endBlock}";
var ms = Regex.Match(textToSearch, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (ms.Groups.TryGetValue("1", out var g))
{
return g.Value;
}
return string.Empty;
}
private static void TestSearchFile()
{
var sep = Environment.NewLine;
var ipAddress6 = "2001:db8:85a3:8d3:1319:8a2e:370:7348";
var ipAddress4 = "10.4.1.10/32";
var t = "Something here..." + sep;
t += "... ... ... " + sep;
t += "interface \"system\"" + sep;
t += "address " + ipAddress4 + sep;
t += "no shutdown" + sep;
t += "exit" + sep;
t += "something here..." + sep;
t += "address 101.4.1.11/32" + sep;
t += "... ... ... " + sep;
var startBlock = "interface \"system\"";
var endBlock = "exit";
var ip = ParseIpWithRegex(t, startBlock, endBlock);
Console.WriteLine($"IP: {ip}");
}
I've included two IP address patterns IPV4_PATTERN for IPV4 only as well as IPV4_IPV6_PATTERN for both IPV4 and IPV6. Select the one you feel is most appropriate. Although the IPV4_IPV6_PATTERN would apply to both IP versions I believe it improves performance slight when the search is narrowed by using the narrowest pattern.
Don't forget to import the Regex reference:
using System.Text.RegularExpressions;
**Code Explained**
The method "ParseIpWithRegex" uses a Regex pattern constructed by using the string that signifies the start of the targeted block and the string that signifies the end of that block. Nestled within that pattern is the regular expressions class definition that defines the IP address pattern we wish to isolate as a group.
$#"{startBlock}\D*\s*({IPV4_IPV6_PATTERN}+).*{endBlock}";
It should be noted that the curly brackets are just for string interpolation and have (in this case) nothing to do with the actual regular expression!
After the "startBlock" we see "\D*". This means that after the "startBlock" include in the search all non-numeric characters (where the "star" indicates to expect zero to infinitely many). Then we see "\s*" which means to include all white space (including new line characters since I included RegexOptions.Singleline).
The IP address pattern is in brackets "()" which instructs Regex to create groups. In this case, behind the IP address pattern (in the above code example IPV4_IPV6_PATTERN) there is a "+" symbol. This indicates that there MUST be at least one of the characters that is in the IP address Regex class definition in order to be considered a "match".
After that we see ".*" in front of the "endBlock". This means to look for any character--including the "new line" character (zero to infinitely many) in from of the "endBlock" string.
If you have any questions, please leave a comment.
EDIT
From your button onclick method you will call SearchFileForIp. You will need to change myTextBox to match your code.
You should also decide whether you will be searching IPV4 or both IPV4 and IPV6 and select the appropriate variable IPV4_PATTERN or IPV4_IPV6_PATTERN.
private void SearchFileForIp()
{
var fileName = "c:\\test.txt";
using var sr = new StreamReader(fileName);
string fileContent = sr.ReadToEnd();
var startBlock = "interface \"system\"";
var endBlock = "exit";
var ip = ParseForIpRegex(fileContent, startBlock, endBlock);
myTextBox.Text = ip; //Change this to match your code
}
private readonly string IPV4_PATTERN = "[0-9./]";
private readonly string IPV4_IPV6_PATTERN = "[A-Z0-9:./]";
private string ParseForIpRegex(string textToSearch, string startBlock, string endBlock)
{
var pattern = $#"{startBlock}\D*\s*({IPV4_PATTERN}+).*{endBlock}";
var ms = Regex.Match(textToSearch, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
if(ms.Groups.Count > 0)
{
return ms.Groups[1].Value;
}
//For .Net Core apps
//if (ms.Groups.TryGetValue("1", out var g))
//{
// return g.Value;
//}
return string.Empty;
}
In addition to the 2 answers with Regex solutions, If address line comes always after interace "system", than a simple for loop can do the job.
interface "system"
address 10.4.1.10/32
no shutdown
exit
So We go thorugh file lines and check if line is interace "system" than take the next value and parse it to string of ip address.
public static string GetIpAddressFromFile(string fileName, string startLine)
{
var lines = File.ReadAllLines(fileName);
var ipAddress = string.Empty;
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line != startLine) continue;
var addressLine = lines[i + 1].Trim().Replace("address", "");
ipAddress = addressLine.Substring(0, addressLine.IndexOf("/", StringComparison.Ordinal));
break;
}
return ipAddress.Trim();
}
Lets assume you that your file is inconsistent and address does not comes first after interface "system"
interface "system"
...
address 10.4.1.10/32
no shutdown
exit
So in this case we put all lines between interface "system" and exit in list of strings, Or dictionary and fetch the address key.
public static string GetIpAddressFromFile(string fileName, string startLine, string endLine)
{
var lines = File.ReadAllLines(fileName);
var ipAddress = string.Empty;
var state = false;
var results = new Dictionary<string, string>();
foreach (var t in lines)
{
var line = t.Trim();
if (line == startLine)
state = true;
if (line == endLine)
state = false;
if (!state) continue;
var s = line.Split(" ");
results.TryAdd(s[0], s[1]);
}
var result = results.GetValueOrDefault("address");
if (result != null)
{
ipAddress = result.Substring(0, result.IndexOf("/", StringComparison.Ordinal));
}
return ipAddress;
}
Usage:
var startLine = "interface \"system\"";
var endLine = "exit";
var ip = GetIpAddressFromFile(#"File.txt", startLine);
//Or
var ip = GetIpAddressFromFile1(#"File.txt", startLine, endLine);
Both methods are tested with your given example and return:
10.4.1.10
If the start of the block and the end of the block are well defined, in order to find the block you can simply:
Search for the start of the block
Do something with the lines until the end of the block
string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null && !line.Equals(START_OF_BLOCK)); // 1.
while((line = file.ReadLine()) != null && !line.Equals(END_OF_BLOCK)) // 2.
{
// do something with the lines
}
file.Close();
Updated answer after edited question:
In order to "extract" the string in a form of an IP address inside the block, you could, for example, use Regular expressions with a .NET Regex class, with previously finding the needed block:
Search for the start of the block
Search for the line inside the block which contains "address"
Extract the IP address from the line using Regexp.Match()
string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
string pat = #"\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pat);
while ((line = Console.ReadLine()) != null && !line.Equals(START_OF_BLOCK)); // 1.
while ((line = Console.ReadLine()) != null && !line.Equals(END_OF_BLOCK)) // 2.
{
if (line.Contains("address"))
{
System.Text.RegularExpressions.Match ip = reg.Match(line);
Console.WriteLine(ip);
break; // break if you are sure there's only one ip in that block
}
}
file.Close();
Here is simple LINQ for that:
var textData = File.ReadAllLines("Path goes here");
var address = string.Join("", textData
.SkipWhile(x => !x.Trim().StartsWith($"interface \"system\""))
.SkipWhile(x => !x.Trim().StartsWith($"address"))
.Take(1)).Split("address")[1].Trim();
SkipWhile goes trough string array until it finds line which starts
like: "interface \"system\"".
Second SkipWhile goes trough part after "interface \"system\"" string until
it finds line which starts like: "address".
Then you Take(1) matching line and create string out of it.
Then you use Split to create new array which contains address text
and ip address.
After that you simply take last part of the array.

Extra character from WWW text (Compare with www.text not working)

I am programming a login system now on Unity, but I have this weird bug. For some reason when I get the output of the php file, the if statement in the C# file can't see that 'loginreturn' (= AccountDoesntExist) and the string "AccountDoesntExist" are the same. I don't know why but maybe you smart people see the bug and can help me out.
C# Code:
IEnumerator TryLogin(string username, string password)
{
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("password", password);
WWW loginWWW = new WWW(LoginURL, form);
yield return loginWWW;
if (!string.IsNullOrEmpty(loginWWW.error))
{
Debug.LogError("Cannot connect to LOGIN servers! Error: " + loginWWW.error);
}else
{
string loginreturn = loginWWW.text;
Debug.Log(loginWWW.text);
Debug.Log(loginreturn);
if (loginreturn == "AccountDoesntExist")
Debug.Log("WORKS!");
}
}
PHP Code (which will always return "AccountDoesntExist" because of the way I log in):
<?php
$inputusername = $_REQUEST["username"];
$password = $_REQUEST["password"];
$servername = "localhost";
$username = "chatsystem_accs";
$password = "CENCORED";
$dbname = "chatsystem_accs";
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Connected successfully
$sql = "SELECT `username`, `password` FROM `accounts`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($inputusername == $row["username"]) {
if (password_verify($password, $row["password"])) {
echo "Success";
}else {
echo "UsernameOrPasswordIncorrect";
}
}else {
echo "AccountDoesntExist";
}
}
}else {
echo "AccountDoesntExist";
}
//Close connection
$conn->close();
?>
Very likely a UTF-8 problem. There is an extra data in the received bytes. Convert the received data to UTF-8 before comparing it.
Replace
string loginreturn = loginWWW.text;
with
string loginreturn = System.Text.Encoding.UTF8.GetString(loginWWW.bytes, 3, loginWWW.bytes.Length - 3);
EDIT:
Did debugging like this:
Debug.Log("Received Length: "+ loginreturn.Length);
Debug.Log("Compare Length: " + "AccountDoesntExist".Length);
and the results were:
Received Length: 19
Compare Length: 18
This is wrong. There is an extra character somewhere.
Debugged again with the function below then called it with displayAsChar(loginreturn);
void displayAsChar(string badValue)
{
char[] values = badValue.ToCharArray();
for (int i = 0; i < values.Length; i++)
{
string tempResult = "Value at index " + i + " is: " + values[i];
Debug.Log(tempResult);
}
}
It shows there is an empty character at the end of the character. I thought that was just " " but it wasn't.
I made another function to see what this empty character is:
void showStringAsHex(string badValue)
{
foreach (char c in badValue)
Debug.Log("To Unicode: " + ((int)c).ToString("X2"));
}
Bingo. That last character is 0A (Hex) which is also represented as \n. This is used as a line feed.
FIX:
Before doing the compare action, trim the string. This will remove any escape character and empty strings in the beginning and end of the character.
To trim the character, simply add the code below before comparing the string.
loginreturn = loginreturn.Trim();
Why post the debugging process?
The characters might be different for different servers. Posting this will help others troubleshoot and fix this problem for them-selves in the future.

I am getting raw text while reading emails using IMAP

I have taken some code from MSDN to read emails using IMAP Client. I have changed little bit code so i can only read unseen email.
I am writing all response in Richtextbox.
The problems is format of Body text of Email is unreadable while all other text is fine.
void ReadEmail()
{
try
{
// there should be no gap between the imap command and the \r\n
// ssl.read() -- while ssl.readbyte!= eof does not work because there is no eof from server
// cannot check for \r\n because in case of larger response from server ex:read email message
// there are lot of lines so \r \n appears at the end of each line
//ssl.timeout sets the underlying tcp connections timeout if the read or write
//time out exceeds then the undelying connection is closed
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
ssl = new System.Net.Security.SslStream(tcpc.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
receiveResponse("");
username = "charlie#gmail.com";
password = "********";
receiveResponse("$ LOGIN " + username + " " + password + " \r\n");
receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n");
receiveResponse("$ SELECT INBOX\r\n");
receiveResponse("$ UID SEARCH UNSEEN\r\n");
MatchCollection collection= Regex.Matches(Result,#" (\d{1,4})");
foreach (Match m in collection)
{
UNREAD_UID.Add(int.Parse(m.Groups[1].Value));
}
foreach (int x in UNREAD_UID)
{
receiveResponse("$ FETCH " +x + " body[header]\r\n");
richTextBox1.Text += Environment.NewLine+"-----------------------------------------------------------------------------------------------------------------------"+Environment.NewLine;
receiveResponse("$ FETCH " +x + " body[text]\r\n");
richTextBox1.Text += Environment.NewLine + "###########################################################2" + Environment.NewLine;
richTextBox1.Update();
}
//receiveResponse("$ STATUS INBOX (MESSAGES)\r\n");
// int number = 1;
receiveResponse("$ LOGOUT\r\n");
}
catch (Exception ex)
{
Console.WriteLine("error: " + ex.Message);
}
finally
{
if (sw != null)
{
sw.Close();
sw.Dispose();
}
if (ssl != null)
{
ssl.Close();
ssl.Dispose();
}
if (tcpc != null)
{
tcpc.Close();
}
}
}
void receiveResponse(string command)
{
try
{
if (command != "")
{
if (tcpc.Connected)
{
dummy = Encoding.ASCII.GetBytes(command);
ssl.Write(dummy, 0, dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
ssl.Flush();
buffer = new byte[5120];
bytes = ssl.Read(buffer, 0, 5120);
sb.Append(Encoding.ASCII.GetString(buffer));
Result = sb.ToString();
richTextBox1.Text += Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + sb.ToString();
sb = new StringBuilder();
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
Here is Sample of what i am getting
108 FETCH (BODY[TEXT] {25656}
DQoNCg0KDQo8IURPQ1RZUEUgaHRtbD4NCjxodG1sPg0KPGhlYWQ+DQo8dGl0bGU+TWlj
cm9zb2Z0IHR1cm5zIChhbG1vc3QpIGFueSBjYW1lcmEgaW50byBhIEtpbmVjdDwvdGl0
bGU+DQo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRleHQv
aHRtbDsgY2hhcnNldD1VVEYtOCI+DQo8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY29udGVu
dD0id2lkdGg9ZGV2aWNlLXdpZHRoIj4NCjwhLS0gRWZmaW5nIFdpbmRvd3MgOCBNYWls
IGNsaWVudC4gQWRkIC13ZWJraXQtbWluLWRldmljZS1waXhlbC1yYXRpbzogMSB0byBz
Y2FyZSBpdCBhd2F5IGZyb20gdGhpcyBiaXQuIC0tPg0KPHN0eWxlIHR5cGU9InRleHQv
Y3NzIj4NCkBtZWRpYSBzY3JlZW4gYW5kIChtYXgtZGV2aWNlLXdpZHRoOiA1MDBweCkg
YW5kICgtd2Via2l0LW1pbi1kZXZpY2UtcGl4ZWwtcmF0aW86IDEpIHsNCgkuYm9keS1j
b250YWluZXIgeyB3aWR0aDoxMDAlICFpbXBvcnRhbnQ7IH0NCgkuYmFubmVyICAgICAg
ICAgeyBkaXNwbGF5OiBub25lICFpbXBvcnRhbnQ7IH0NCgkubW9iaWxlLWJhbm5lciAg
eyBkaXNwbGF5OiBibG9jayAhaW1wb3J0YW50OyB3aWR0aDozNDBweCAhaW1wb3J0YW50
OyBiYWNrZ3JvdW5kOiB1cmwoaHR0cDovL3d3dy5jb2RlcHJvamVjdC5jb20vc2NyaXB0
L21haWxvdXRzL3RlbXBsYXRlcy9uZXdzbGV0dGVyLWluc2lkZXIucG5nKSBuby1yZXBl
YXQgdG9wIGxlZ
Kindly help me.
You need to examine the Content-Transfer-Encoding header to undo Transfer encoding (in this case, that's Base64. Other alternatives are 7-bit or Quoted Printable). Or, better, download the entire message (Body[]) and apply a MIME parser/decoder to it to get an object representation of the headers, body, and attachments.
Max's answer above is correct, but I'm going to illustrate how to implement his suggestion using my MailKit library:
using (var client = new ImapClient ()) {
client.Connect ("imap.gmail.com", 993, true);
// since we're not using an OAuth2 token, remove it from the set
// of possible authentication mechanisms to try:
client.AuthenticationMechanisms.Remove ("XOAUTH2");
client.Authenticate ("charlie#gmail.com", "*****");
// SELECT the INBOX folder
client.Inbox.Open (FolderAccess.ReadWrite);
foreach (var uid in client.Inbox.Search (SearchQuery.NotSeen)) {
var message = client.Inbox.GetMessage (uid);
// at this point, 'message' is a MIME DOM that you can walk
// over to get the particular MIME-part that you want. For
// example, we could get a body part with a filename of
// "test.txt" using LINQ like this:
var attachment = message.BodyParts.OfType<MimePart> ()
.FirstOrDefault (x => x.FileName == "test.txt");
// decode the content to a MemoryStream:
using (var memory = new MemoryStream ()) {
attachment.ContentObject.DecodeTo (memory);
}
// since the attachment is probably a TextPart
// (based on the file extension above), we can actually
// use a simpler approach:
var textPart = attachment as TextPart;
if (textPart != null) {
// decode the content and convert into a 'string'
var text = textPart.Text;
}
}
client.Disconnect (true);
}

Errors in my program to read IP addresses from server log files

I'm new to C# and have a question.
My server has log files with lines like
2015-05-14 20:56:50 72.167.255.87 GET
/images/email/site_05_12_2015/email-contactus-button.png
- 80 - 50.48.46.50 Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.2;+WOW64;+Trident/7.0;+Microsoft+Outlook+15.0.4711;+Microsoft+Outlook+15.0.4711;+ms-office;+MSOffice+15)
304 0 0 46
and my program is intended to collect the unique IP addresses that request a certain asset. In the above line I would extract "50.48.46.50" if the program was searching for "email-contactus-button.png".
Here it is:
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
class Test
{
static void Main(string[] args)
{
// args[0] = expression to search for, e.g. "cloudrealized-email-top-banner"
try
{
string [] logs = System.IO.Directory.GetFiles(System.IO.Directory.GetCurrentDirectory());
Console.WriteLine("{0} log files found", logs.Length);
HashSet<string> ipList;
string ipreg = "^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$";
foreach (string thislog in logs)
{
using (StreamReader sr = new StreamReader(thislog))
{
Console.WriteLine("Checking log file {0} for expression '{1}' ...\n", thislog, args[0]);
String line = sr.ReadToEnd();
if (line.Contains(args[0]))
{
Match thisip = Regex.Match(line,ipreg);
thisip = thisip.NextMatch();
if (thisip.ToString() != args[1]) ipList.Add(thisip);
}
//for (Match m = Regex.Match(line,regx); m.Success; m = m.NextMatch()) ++count;
}
}
Console.WriteLine("\n\nRESULT:\n\nThe asset {0} was requested {1} times.", args[0], ipList.Count());
Console.WriteLine("Unique IPs:");
foreach (string s in ipList) Console.WriteLine(s);
}
catch (Exception e)
{
Console.WriteLine("Error occured: ");
Console.WriteLine(e.Message);
}
}
}
The first compiler warning I'm getting is on the line
string ipreg = "^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$";
because it thinks I'm trying to escape the . character. How can I fix that?
The other two warnings are on the methods I call on iplist. They are not recognized, and I can't figure out why. The documentation I was looking at for HashSet is https://msdn.microsoft.com/en-us/library/bb359438%28v=vs.110%29.aspx.
Here is a basic C# example of a regex expression to pull out that IP address. This is assuming that all of your log files will be structured the same way.
string strRegex = #"(?<=-\s)([0-9]{1,3}\.){3}[0-9]{1,3}";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = #"2015-05-14 20:56:50 72.167.255.87 GET /images/email/site_05_12_2015/email-contactus-button.png - 80 - 50.48.46.50 Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.2;+WOW64;+Trident/7.0;+Microsoft+Outlook+15.0.4711;+Microsoft+Outlook+15.0.4711;+ms-office;+MSOffice+15) 304 0 0 46";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}

SharpPcap - A Packet Capture getting messesge problem

I trying to capture packets using SharpPcap library.
I'm able to return the packets details but I'm having problem to get what the message content inside the packet.
the packet using .Data to return the message and when I use it it is returning (System.Byte[]).
here is the library website:
http://www.codeproject.com/KB/IP/sharppcap.aspx
here is my code:
string packetData;
private void packetCapturingThreadMethod()
{
Packet packet = null;
int countOfPacketCaptures = 0;
while ((packet = device.GetNextPacket()) != null)
{
packet = device.GetNextPacket();
if (packet is TCPPacket)
{
TCPPacket tcp = (TCPPacket)packet;
myPacket tempPacket = new myPacket();
tempPacket.packetType = "TCP";
tempPacket.sourceAddress = Convert.ToString(tcp.SourceAddress);
tempPacket.destinationAddress = Convert.ToString(tcp.DestinationAddress);
tempPacket.sourcePort = Convert.ToString(tcp.SourcePort);
tempPacket.destinationPort = Convert.ToString(tcp.DestinationPort);
tempPacket.packetMessage = Convert.ToString(tcp.Data);
packetsList.Add(tempPacket);
packetData =
"Type= TCP" +
" Source Address = "+ Convert.ToString(tcp.SourceAddress)+
" Destination Address =" +Convert.ToString(tcp.DestinationAddress)+
" SourcePort =" + Convert.ToString(tcp.SourcePort)+
" SourcePort =" +Convert.ToString(tcp.DestinationPort)+
" Messeage =" + Convert.ToString(tcp.Data);
txtpackets.Invoke(new UpdatetxtpacketsCallback(this.Updatetxtpackets),
new object[] { packetData });
string[] row = { packetsList[countOfPacketCaptures].packetType, packetsList[countOfPacketCaptures].sourceAddress, packetsList[countOfPacketCaptures].destinationAddress, packetsList[countOfPacketCaptures].sourcePort, packetsList[countOfPacketCaptures].destinationPort, packetsList[countOfPacketCaptures].packetMessage };
try { //dgwPacketInfo.Rows.Add(row); countOfPacketCaptures++;
//lblCapturesLabels.Text = Convert.ToString(countOfPacketCaptures);
}
catch (Exception e) { }
}
else if (packet is UDPPacket)
{
UDPPacket udp = (UDPPacket)packet;
myPacket tempPacket = new myPacket();
tempPacket.packetType = "UDP";
tempPacket.sourceAddress = Convert.ToString(udp.SourceAddress);
tempPacket.destinationAddress = Convert.ToString(udp.DestinationAddress);
tempPacket.sourcePort = Convert.ToString(udp.SourcePort);
tempPacket.destinationPort = Convert.ToString(udp.DestinationPort);
tempPacket.packetMessage = udp.Data.ToArray() + "\n";
packetsList.Add(tempPacket);
packetData =
"Type= UDP" +
" Source Address = "+ Convert.ToString(udp.SourceAddress)+
" Destination Address =" +Convert.ToString(udp.DestinationAddress)+
" SourcePort =" + Convert.ToString(udp.SourcePort)+
" SourcePort =" +Convert.ToString(udp.DestinationPort)+
" Messeage =" + udp.Data.ToArray() + "\n";
string[] row = { packetsList[countOfPacketCaptures].packetType, packetsList[countOfPacketCaptures].sourceAddress, packetsList[countOfPacketCaptures].destinationAddress, packetsList[countOfPacketCaptures].sourcePort, packetsList[countOfPacketCaptures].destinationPort, packetsList[countOfPacketCaptures].packetMessage };
try {
//dgwPacketInfo.Rows.Add(row);
//countOfPacketCaptures++;
//lblCapturesLabels.Text = Convert.ToString(countOfPacketCaptures);
txtpackets.Invoke(new UpdatetxtpacketsCallback(this.Updatetxtpackets),
new object[] { packetData });
}
catch (Exception e) { }
}
}
}
I found the answer...
Data is a byte array so I need to use bit converter and instead of using:
Convert.ToString(tcp.Data);
I should use:
BitConverter.ToString(tcp.Data)
The parser isn't that complex...
I looked at the Packet.Net code (which is the parse for SharpPcap) and all of the fields are stored in commonly used formats.
The IP Addresses are stored in System.Net.IPAddress format so you can just call .ToString on them to get a text string that properly includes the dot marks.
The port numbers are stored as ushort which can be printed the same as any other integer.
The only part that needs to be interpreted in its binary form is the Data field because that changes based on what protocol is being used on the next layer up. SharpPcap/Packet.Net does most of the work for you already and fields are stored in the most convenient or identical forms to those found in the protocol specification. Just use intellisense to check the field's type and if it's not one you're familiar with (such as System.Net.IPAddress or System.NetworkInformation.PhysicalAddress (For MAC addresses)) just google it.

Categories