com port identification by device serial number [duplicate] - c#

This question already has answers here:
Getting Serial Port Information
(8 answers)
Closed 14 days ago.
In our company for testing purposes, we use many serial COM port devices. These devices are transferred daily between several PC and whenever we add a new serial device, we have to manualy learn on all computers.
Currently I am working on code, for automatic COM port device detection. My question is, how to list also device ID in c++ or c# next to the active COM port list?
With serial number, I will be able to automatically detect on what port device is on on each PC.
Also for FTDI, Silicon Labs,..USB to RS232 converter I can manualy set device SN. Solution need to work on windows 7 or newer.
For example:
My code:
static void Main(string[] args)
{
// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach (string port in ports)
{
Console.WriteLine(port);
}
Console.ReadLine();
}

You can use ManagementObjectSearcher for this. You'll need to add System.Management as a reference.
using System;
using System.Management; // need to add System.Management to your project references
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * From Win32_USBHub");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("USB device");
Console.WriteLine("Caption: {0}", queryObj["Caption"]);
Console.WriteLine("Description: {0}", queryObj["Description"]);
Console.WriteLine("DeviceID: {0}", queryObj["DeviceID"]);
Console.WriteLine("Name: {0}", queryObj["Name"]);
Console.WriteLine("PNPDeviceID: {0}", queryObj["PNPDeviceID"]);
}

I found a working code check this post Getting Serial Port Information
Code:
using System.Management;
using Microsoft.Win32;
using (ManagementClass i_Entity = new ManagementClass("Win32_PnPEntity"))
{
foreach (ManagementObject i_Inst in i_Entity.GetInstances())
{
Object o_Guid = i_Inst.GetPropertyValue("ClassGuid");
if (o_Guid == null || o_Guid.ToString().ToUpper() != "{4D36E978-E325-11CE-BFC1-08002BE10318}")
continue; // Skip all devices except device class "PORTS"
String s_Caption = i_Inst.GetPropertyValue("Caption") .ToString();
String s_Manufact = i_Inst.GetPropertyValue("Manufacturer").ToString();
String s_DeviceID = i_Inst.GetPropertyValue("PnpDeviceID") .ToString();
String s_RegPath = "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\" + s_DeviceID + "\\Device Parameters";
String s_PortName = Registry.GetValue(s_RegPath, "PortName", "").ToString();
int s32_Pos = s_Caption.IndexOf(" (COM");
if (s32_Pos > 0) // remove COM port from description
s_Caption = s_Caption.Substring(0, s32_Pos);
Console.WriteLine("Port Name: " + s_PortName);
Console.WriteLine("Description: " + s_Caption);
Console.WriteLine("Manufacturer: " + s_Manufact);
Console.WriteLine("Device ID: " + s_DeviceID);
Console.WriteLine("-----------------------------------");
}
Console.ReadLine();
}
Console output:
Port Name: COM29
Description: CDC Interface (Virtual COM Port) for USB Debug
Manufacturer: GHI Electronics, LLC
Device ID: USB\VID_1B9F&PID_F003&MI_01\6&3009671A&0&0001
-----------------------------------
Port Name: COM28
Description: Teensy USB Serial
Manufacturer: PJRC.COM, LLC.
Device ID: USB\VID_16C0&PID_0483\1256310
-----------------------------------
Port Name: COM25
Description: USB-SERIAL CH340
Manufacturer: wch.cn
Device ID: USB\VID_1A86&PID_7523\5&2499667D&0&3
-----------------------------------
Port Name: COM26
Description: Prolific USB-to-Serial Comm Port
Manufacturer: Prolific
Device ID: USB\VID_067B&PID_2303\5&2499667D&0&4
-----------------------------------
Port Name: COM1
Description: Comunications Port
Manufacturer: (Standard port types)
Device ID: ACPI\PNP0501\1
-----------------------------------
Port Name: COM999
Description: EPSON TM Virtual Port Driver
Manufacturer: EPSON
Device ID: ROOT\PORTS\0000
-----------------------------------
Port Name: COM20
Description: EPSON COM Emulation USB Port
Manufacturer: EPSON
Device ID: ROOT\PORTS\0001
-----------------------------------
Port Name: COM8
Description: Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID: BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&000F\8&3ADBDF90&0&001DA568988B_C00000000
-----------------------------------
Port Name: COM9
Description: Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID: BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\8&3ADBDF90&0&000000000000_00000002
-----------------------------------
Port Name: COM30
Description: Arduino Uno
Manufacturer: Arduino LLC (www.arduino.cc)
Device ID: USB\VID_2341&PID_0001\74132343530351F03132
-----------------------------------

If I understood your questions correctly, the C++ code below should help.
Edit: added support for friendly name (which includes COM number).
On my system I get this result, which seems to match your screenshots:
installed serial devices:
Dev. Id: PCI\VEN_8086&DEV_9D3D&SUBSYS_506D17AA&REV_21\3&11583659&1&B3
friendly name: Intel(R) Active Management Technology - SOL (COM3)
Dev. Id: FTDIBUS\VID_0403+PID_6001+A916RGSAA\0000
friendly name: USB Serial Port (COM4)
device interfaces:
Interface: \\?\PCI#VEN_8086&DEV_9D3D&SUBSYS_506D17AA&REV_21#3&11583659&1&B3#{86e0d1e0-8089-11d0-9ce4-08003e301f73}
Interface: \\?\FTDIBUS#VID_0403+PID_6001+A916RGSAA#0000#{86e0d1e0-8089-11d0-9ce4-08003e301f73}
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <initguid.h>
#include <windows.h>
#include <devpkey.h>
#include <cfgmgr32.h>
auto splitListAsString(const std::wstring_view& s)
{
std::vector<std::wstring> l;
for (size_t pos{ 0 }; s.at(pos) != 0;) {
auto newpos = s.find(L'\0', pos);
l.emplace_back(s.substr(pos, newpos - pos));
pos = newpos + 1;
}
return l;
}
int main()
{
wchar_t guid_str[] = L"{4D36E978-E325-11CE-BFC1-08002BE10318}";
auto propKey{ DEVPKEY_Device_FriendlyName };
ULONG len{};
auto res = CM_Get_Device_ID_List_Size(&len, guid_str, CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT);
if (res != CR_SUCCESS) {
std::cerr << "error num " << res << " occured\n";
return -1;
}
std::wstring devIds(len,'\0');
res = CM_Get_Device_ID_ListW(guid_str, devIds.data(), len, CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT);
std::wcout << L"installed serial devices:\n";
for (auto& e : splitListAsString(devIds)) {
std::wcout << L"Dev. Id: " << e << L'\n';
DEVINST devInst{};
res = CM_Locate_DevInstW(&devInst, e.data(), CM_LOCATE_DEVNODE_NORMAL);
if (res != CR_SUCCESS) {
std::cerr << "error locating device " << res << " occured\n";
continue;
}
DEVPROPTYPE devpropt{};
CM_Get_DevNode_PropertyW(devInst, &propKey, &devpropt, nullptr, &len, 0);
if (res!=CR_BUFFER_SMALL && res != CR_SUCCESS) {
std::cerr << "error " << res << "\n";
continue;
//return -1;
}
auto buffer = std::make_unique<BYTE[]>(len);
res = CM_Get_DevNode_PropertyW(devInst, &propKey, &devpropt, buffer.get(), &len, 0);
if (devpropt == DEVPROP_TYPE_STRING) {
const auto val = reinterpret_cast<wchar_t*>(buffer.get());
std::wcout << L"friendly name: " << val << L"\n\n";
}
}
auto guid_comport_interface{ GUID_DEVINTERFACE_COMPORT };
res = CM_Get_Device_Interface_List_SizeW(&len, &guid_comport_interface, nullptr, CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
if (res != CR_SUCCESS) {
std::cerr << "error num " << res << " occured\n";
return -1;
}
std::wstring devInterfaces(len, '\0');
res = CM_Get_Device_Interface_ListW(&guid_comport_interface, nullptr, devInterfaces.data(), len, CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
std::wcout << L"\ndevice interfaces:\n";
for (const auto& e : splitListAsString(devInterfaces)) {
std::wcout << L"Interface: " << e << '\n';
}
}

Related

connect to Bitcoin core from c#

i download bitcoin core from here https://bitcoin.org/en/download and try to connect to it from c# i use the demo code from here https://github.com/cryptean/bitcoinlib i set bitcoin.conf
like this:
rpcport=8332
rpcuser=myuser
rpcpass=mypass
txindex=1
and here is app.config:
<!-- Bitcoin settings start -->
<add key="Bitcoin_DaemonUrl" value="http://127.0.0.1:8332" />
<add key="Bitcoin_DaemonUrl_Testnet" value="http://127.0.0.1:18332" />
<add key="Bitcoin_WalletPassword" value="" />
<add key="Bitcoin_RpcUsername" value="myuser" />
<add key="Bitcoin_RpcPassword" value="mypass" />
<!-- Bitcoin settings end -->
and when i run the demo , error happened , here is the error message :
Connecting to Bitcoin MainNet via RPC at http://127.0.0.1:8332...The RPC request was either not understood by the server or there was a problem executing the request
at BitcoinLib.RPC.Connector.RpcConnector.MakeRequest[T](RpcMethods rpcMethod, Object[] parameters) in C:\Users\pc\Downloads\bitcoinlib-master\bitcoinlib-master\src\BitcoinLib\RPC\Connector\RpcConnector.cs:line 125
at BitcoinLib.Services.CoinService.GetDifficulty() in C:\Users\pc\Downloads\bitcoinlib-master\bitcoinlib-master\src\BitcoinLib\Services\RpcServices\RpcService\RpcService.cs:line 225
at ConsoleClient.Program.Main() in C:\Users\pc\Downloads\bitcoinlib-master\bitcoinlib-master\demo\Program.cs:line 104
i am not use testnet here is the code:
private static void Main()
{
try
{
var data = RequestServer("getblockcount", new List<string>() { "value" });
Console.WriteLine(data);
return;
Console.Write("\n\nConnecting to {0} {1}Net via RPC at {2}...", CoinService.Parameters.CoinLongName, (CoinService.Parameters.UseTestnet ? "Test" : "Main"), CoinService.Parameters.SelectedDaemonUrl);
// Network difficulty
var networkDifficulty = CoinService.GetDifficulty();
// networkDifficulty.ToString();
Console.WriteLine("[OK]\n\n{0} Network Difficulty: {1}", CoinService.Parameters.CoinLongName, networkDifficulty.ToString("#,###", CultureInfo.InvariantCulture));
// Mining info
var miningInfo = CoinService.GetMiningInfo();
Console.WriteLine("[OK]\n\n{0} NetworkHashPS: {1}", CoinService.Parameters.CoinLongName, miningInfo.NetworkHashPS.ToString("#,###", CultureInfo.InvariantCulture));
// My balance
var myBalance = CoinService.GetBalance();
Console.WriteLine("\nMy balance: {0} {1}", myBalance, CoinService.Parameters.CoinShortName);
// Current block
Console.WriteLine("Current block: {0}",
CoinService.GetBlockCount().ToString("#,#", CultureInfo.InvariantCulture));
// Wallet state
Console.WriteLine("Wallet state: {0}", CoinService.IsWalletEncrypted() ? "Encrypted" : "Unencrypted");
// Keys and addresses
if (myBalance > 0)
{
// My non-empty addresses
Console.WriteLine("\n\nMy non-empty addresses:");
var myNonEmptyAddresses = CoinService.ListReceivedByAddress();
foreach (var address in myNonEmptyAddresses)
{
Console.WriteLine("\n--------------------------------------------------");
Console.WriteLine("Account: " + (string.IsNullOrWhiteSpace(address.Account) ? "(no label)" : address.Account));
Console.WriteLine("Address: " + address.Address);
Console.WriteLine("Amount: " + address.Amount);
Console.WriteLine("Confirmations: " + address.Confirmations);
Console.WriteLine("--------------------------------------------------");
}
// My private keys
if (bool.Parse(ConfigurationManager.AppSettings["ExtractMyPrivateKeys"]) && myNonEmptyAddresses.Count > 0 && CoinService.IsWalletEncrypted())
{
const short secondsToUnlockTheWallet = 30;
Console.Write("\nWill now unlock the wallet for " + secondsToUnlockTheWallet + ((secondsToUnlockTheWallet > 1) ? " seconds" : " second") + "...");
CoinService.WalletPassphrase(CoinService.Parameters.WalletPassword, secondsToUnlockTheWallet);
Console.WriteLine("[OK]\n\nMy private keys for non-empty addresses:\n");
foreach (var address in myNonEmptyAddresses)
{
Console.WriteLine("Private Key for address " + address.Address + ": " + CoinService.DumpPrivKey(address.Address));
}
Console.Write("\nLocking wallet...");
CoinService.WalletLock();
Console.WriteLine("[OK]");
}
// My transactions
Console.WriteLine("\n\nMy transactions: ");
var myTransactions = CoinService.ListTransactions(null, int.MaxValue, 0);
foreach (var transaction in myTransactions)
{
Console.WriteLine("\n---------------------------------------------------------------------------");
Console.WriteLine("Account: " + (string.IsNullOrWhiteSpace(transaction.Account) ? "(no label)" : transaction.Account));
Console.WriteLine("Address: " + transaction.Address);
Console.WriteLine("Category: " + transaction.Category);
Console.WriteLine("Amount: " + transaction.Amount);
Console.WriteLine("Fee: " + transaction.Fee);
Console.WriteLine("Confirmations: " + transaction.Confirmations);
Console.WriteLine("BlockHash: " + transaction.BlockHash);
Console.WriteLine("BlockIndex: " + transaction.BlockIndex);
Console.WriteLine("BlockTime: " + transaction.BlockTime + " - " + UnixTime.UnixTimeToDateTime(transaction.BlockTime));
Console.WriteLine("TxId: " + transaction.TxId);
Console.WriteLine("Time: " + transaction.Time + " - " + UnixTime.UnixTimeToDateTime(transaction.Time));
Console.WriteLine("TimeReceived: " + transaction.TimeReceived + " - " + UnixTime.UnixTimeToDateTime(transaction.TimeReceived));
if (!string.IsNullOrWhiteSpace(transaction.Comment))
{
Console.WriteLine("Comment: " + transaction.Comment);
}
if (!string.IsNullOrWhiteSpace(transaction.OtherAccount))
{
Console.WriteLine("Other Account: " + transaction.OtherAccount);
}
if (transaction.WalletConflicts != null && transaction.WalletConflicts.Any())
{
Console.Write("Conflicted Transactions: ");
foreach (var conflictedTxId in transaction.WalletConflicts)
{
Console.Write(conflictedTxId + " ");
}
Console.WriteLine();
}
Console.WriteLine("---------------------------------------------------------------------------");
}
// Transaction Details
Console.WriteLine("\n\nMy transactions' details:");
foreach (var transaction in myTransactions)
{
// Move transactions don't have a txId, which this logic fails for
if (transaction.Category == "move")
{
continue;
}
var localWalletTransaction = CoinService.GetTransaction(transaction.TxId);
IEnumerable<PropertyInfo> localWalletTrasactionProperties = localWalletTransaction.GetType().GetProperties();
IList<GetTransactionResponseDetails> localWalletTransactionDetailsList = localWalletTransaction.Details.ToList();
Console.WriteLine("\nTransaction\n-----------");
foreach (var propertyInfo in localWalletTrasactionProperties)
{
var propertyInfoName = propertyInfo.Name;
if (propertyInfoName != "Details" && propertyInfoName != "WalletConflicts")
{
Console.WriteLine(propertyInfoName + ": " + propertyInfo.GetValue(localWalletTransaction, null));
}
}
foreach (var details in localWalletTransactionDetailsList)
{
IEnumerable<PropertyInfo> detailsProperties = details.GetType().GetProperties();
Console.WriteLine("\nTransaction details " + (localWalletTransactionDetailsList.IndexOf(details) + 1) + " of total " + localWalletTransactionDetailsList.Count + "\n--------------------------------");
foreach (var propertyInfo in detailsProperties)
{
Console.WriteLine(propertyInfo.Name + ": " + propertyInfo.GetValue(details, null));
}
}
}
// Unspent transactions
Console.WriteLine("\nMy unspent transactions:");
var unspentList = CoinService.ListUnspent();
foreach (var unspentResponse in unspentList)
{
IEnumerable<PropertyInfo> detailsProperties = unspentResponse.GetType().GetProperties();
Console.WriteLine("\nUnspent transaction " + (unspentList.IndexOf(unspentResponse) + 1) + " of " + unspentList.Count + "\n--------------------------------");
foreach (var propertyInfo in detailsProperties)
{
Console.WriteLine(propertyInfo.Name + " : " + propertyInfo.GetValue(unspentResponse, null));
}
}
}
Console.ReadLine();
}
catch (RpcInternalServerErrorException exception)
{
var errorCode = 0;
var errorMessage = string.Empty;
if (exception.RpcErrorCode.GetHashCode() != 0)
{
errorCode = exception.RpcErrorCode.GetHashCode();
errorMessage = exception.RpcErrorCode.ToString();
}
Console.WriteLine("[Failed] {0} {1} {2}", exception.Message, errorCode != 0 ? "Error code: " + errorCode : string.Empty, !string.IsNullOrWhiteSpace(errorMessage) ? errorMessage : string.Empty);
}
catch (Exception exception)
{
//Console.WriteLine("[Failed]\n\nPlease check your configuration and make sure that the daemon is up and running and that it is synchronized. \n\nException: " + exception);
Console.WriteLine(exception.Message+"\n"+exception.StackTrace.ToString());
}
}
also i try this code:
public static string RequestServer(string methodName, List<string> parameters)
{
string ServerIp = "http://127.0.0.1:8332";
string UserName = "myuser";
string Password = "mypass";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(ServerIp);
webRequest.Credentials = new NetworkCredential(UserName, Password);
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
string respVal = string.Empty;
JObject joe = new JObject();
joe.Add(new JProperty("jsonrpc", "1.0"));
joe.Add(new JProperty("id", "1"));
joe.Add(new JProperty("method", methodName));
JArray props = new JArray();
foreach (var parameter in parameters)
{
props.Add(parameter);
}
joe.Add(new JProperty("params", props));
// serialize json for the request
string s = JsonConvert.SerializeObject(joe);
byte[] byteArray = Encoding.UTF8.GetBytes(s);
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
StreamReader streamReader = null;
try
{
WebResponse webResponse = webRequest.GetResponse();
streamReader = new StreamReader(webResponse.GetResponseStream(), true);
respVal = streamReader.ReadToEnd();
var data = JsonConvert.DeserializeObject(respVal).ToString();
return data;
}
catch (Exception exp)
{
Console.WriteLine(exp.Message + "\n" + exp.StackTrace.ToString());
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
}
return string.Empty;
}
var data = RequestServer("getblockcount", new List<string>() { "value" });
Console.WriteLine(data);
but error happened:
401 unauthorized ....
i run bitcoind from command:
bitcoind.exe -server
here is the output:
C:\Program Files\Bitcoin\daemon>bitcoind.exe -server
2023-01-01T19:01:43Z Ignoring unknown configuration value rpcpass
2023-01-01T19:01:43Z Bitcoin Core version v22.0.0 (release build)
2023-01-01T19:01:43Z Assuming ancestors of block 00000000000000000008a89e854d57e5667df88f1cdef6fde2fbca1de5b639ad have valid signatures.
2023-01-01T19:01:43Z Setting nMinimumChainWork=00000000000000000000000000000000000000001fa4663bbbe19f82de910280
2023-01-01T19:01:43Z Using the 'shani(1way,2way)' SHA256 implementation
2023-01-01T19:01:43Z Using RdSeed as additional entropy source
2023-01-01T19:01:43Z Using RdRand as an additional entropy source
2023-01-01T19:01:43Z Default data directory C:\Users\pc\AppData\Roaming\Bitcoin
2023-01-01T19:01:43Z Using data directory C:\Users\pc\AppData\Roaming\Bitcoin
2023-01-01T19:01:43Z Config file: C:\Users\pc\AppData\Roaming\Bitcoin\bitcoin.conf
2023-01-01T19:01:43Z Config file arg: rpcport="8332"
2023-01-01T19:01:43Z Config file arg: rpcuser=****
2023-01-01T19:01:43Z Config file arg: server="1"
2023-01-01T19:01:43Z Config file arg: txindex="1"
2023-01-01T19:01:43Z Setting file arg: wallet = ["btc1313"]
2023-01-01T19:01:43Z Command-line arg: server=""
2023-01-01T19:01:43Z Using at most 125 automatic connections (2048 file descriptors available)
2023-01-01T19:01:43Z Using 16 MiB out of 32/2 requested for signature cache, able to store 524288 elements
2023-01-01T19:01:43Z Using 16 MiB out of 32/2 requested for script execution cache, able to store 524288 elements
2023-01-01T19:01:43Z Script verification uses 7 additional threads
2023-01-01T19:01:43Z scheduler thread start
2023-01-01T19:01:43Z HTTP: creating work queue of depth 16
2023-01-01T19:01:43Z Using random cookie authentication.
2023-01-01T19:01:43Z Generated RPC authentication cookie C:\Users\pc\AppData\Roaming\Bitcoin\.cookie
2023-01-01T19:01:43Z HTTP: starting 4 worker threads
2023-01-01T19:01:43Z Using wallet directory C:\Users\pc\AppData\Roaming\Bitcoin\wallets
2023-01-01T19:01:43Z init message: Verifying wallet(s)…
2023-01-01T19:01:43Z Using BerkeleyDB version Berkeley DB 4.8.30: (April 9, 2010)
2023-01-01T19:01:43Z Using wallet C:\Users\pc\AppData\Roaming\Bitcoin\wallets\btc1313\wallet.dat
2023-01-01T19:01:43Z BerkeleyEnvironment::Open: LogDir=C:\Users\pc\AppData\Roaming\Bitcoin\wallets\btc1313\database ErrorFile=C:\Users\pc\AppData\Roaming\Bitcoin\wallets\btc1313\db.log
2023-01-01T19:01:43Z init message: Loading banlist…
2023-01-01T19:01:43Z SetNetworkActive: true
2023-01-01T19:01:43Z Using /16 prefix for IP bucketing
2023-01-01T19:01:43Z Cache configuration:
2023-01-01T19:01:43Z * Using 2.0 MiB for block index database
2023-01-01T19:01:43Z * Using 56.0 MiB for transaction index database
2023-01-01T19:01:43Z * Using 8.0 MiB for chain state database
2023-01-01T19:01:43Z * Using 384.0 MiB for in-memory UTXO set (plus up to 286.1 MiB of unused mempool space)
2023-01-01T19:01:43Z init message: Loading block index…
2023-01-01T19:01:43Z Switching active chainstate to Chainstate [ibd] # height -1 (null)
2023-01-01T19:01:43Z Opening LevelDB in C:\Users\pc\AppData\Roaming\Bitcoin\blocks\index
2023-01-01T19:01:43Z Opened LevelDB successfully
2023-01-01T19:01:43Z Using obfuscation key for C:\Users\pc\AppData\Roaming\Bitcoin\blocks\index: 0000000000000000
2023-01-01T19:01:48Z LoadBlockIndexDB: last block file = 3337
2023-01-01T19:01:48Z LoadBlockIndexDB: last block file info: CBlockFileInfo(blocks=82, size=82069535, heights=769632...769908, time=2022-12-31...2023-01-01)
2023-01-01T19:01:48Z Checking all blk files are present...
2023-01-01T19:01:49Z Opening LevelDB in C:\Users\pc\AppData\Roaming\Bitcoin\chainstate
2023-01-01T19:01:49Z Opened LevelDB successfully
2023-01-01T19:01:49Z Using obfuscation key for C:\Users\pc\AppData\Roaming\Bitcoin\chainstate: 6343dde5e7e6e386
2023-01-01T19:01:49Z Loaded best chain: hashBestChain=000000000000000000039b1c6364ff45a20a879f9a834fe4ed5292cf63cf942a height=769908 date=2023-01-01T18:50:35Z progress=0.999998
2023-01-01T19:01:49Z init message: Verifying blocks…
2023-01-01T19:01:49Z Verifying last 6 blocks at level 3
2023-01-01T19:01:49Z [0%]...[16%]...[33%]...[50%]...[66%]...[83%]...[99%]...[DONE].
2023-01-01T19:01:56Z No coin database inconsistencies in last 6 blocks (9918 transactions)
2023-01-01T19:01:56Z block index 12583ms
2023-01-01T19:01:56Z Opening LevelDB in C:\Users\pc\AppData\Roaming\Bitcoin\indexes\txindex
2023-01-01T19:01:56Z Opened LevelDB successfully
2023-01-01T19:01:56Z Using obfuscation key for C:\Users\pc\AppData\Roaming\Bitcoin\indexes\txindex: 0000000000000000
2023-01-01T19:01:56Z txindex thread start
2023-01-01T19:01:56Z init message: Loading wallet…
2023-01-01T19:01:56Z txindex is enabled at height 769908
2023-01-01T19:01:56Z txindex thread exit
2023-01-01T19:01:56Z BerkeleyEnvironment::Open: LogDir=C:\Users\pc\AppData\Roaming\Bitcoin\wallets\btc1313\database ErrorFile=C:\Users\pc\AppData\Roaming\Bitcoin\wallets\btc1313\db.log
2023-01-01T19:01:56Z [btc1313] Wallet File Version = 169900
2023-01-01T19:01:56Z [btc1313] Keys: 2001 plaintext, 0 encrypted, 2001 w/ metadata, 2001 total. Unknown wallet records: 0
2023-01-01T19:01:56Z [btc1313] Wallet completed loading in 53ms
2023-01-01T19:01:56Z [btc1313] setKeyPool.size() = 2000
2023-01-01T19:01:56Z [btc1313] mapWallet.size() = 0
2023-01-01T19:01:56Z [btc1313] m_address_book.size() = 0
2023-01-01T19:01:56Z block tree size = 769909
2023-01-01T19:01:56Z nBestHeight = 769908
2023-01-01T19:01:56Z loadblk thread start
2023-01-01T19:01:56Z torcontrol thread start
2023-01-01T19:01:56Z Bound to 127.0.0.1:8334
2023-01-01T19:01:56Z Bound to [::]:8333
2023-01-01T19:01:56Z Bound to 0.0.0.0:8333
2023-01-01T19:01:56Z Leaving InitialBlockDownload (latching to false)
2023-01-01T19:01:56Z init message: Loading P2P addresses…
2023-01-01T19:01:56Z Loaded 63213 addresses from peers.dat 116ms
2023-01-01T19:01:56Z Loaded 2 addresses from "anchors.dat"
2023-01-01T19:01:56Z 2 block-relay-only anchors will be tried for connections.
2023-01-01T19:01:56Z init message: Starting network threads…
2023-01-01T19:01:56Z opencon thread start
2023-01-01T19:01:56Z addcon thread start
2023-01-01T19:01:56Z dnsseed thread start
2023-01-01T19:01:56Z Waiting 300 seconds before querying DNS seeds.
2023-01-01T19:01:56Z msghand thread start
2023-01-01T19:01:56Z init message: Done loading
2023-01-01T19:01:56Z net thread start
2023-01-01T19:01:57Z Imported mempool transactions from disk: 695 succeeded, 0 failed, 0 expired, 0 already there, 0 waiting for initial broadcast
2023-01-01T19:01:57Z loadblk thread exit
2023-01-01T19:01:57Z New outbound peer connected: version: 70016, blocks=769909, peer=0 (block-relay-only)
2023-01-01T19:01:58Z New outbound peer connected: version: 70015, blocks=769909, peer=1 (block-relay-only)
2023-01-01T19:01:59Z New outbound peer connected: version: 70016, blocks=769909, peer=2 (outbound-full-relay)
2023-01-01T19:02:04Z UpdateTip: new best=00000000000000000006266ea0383ab08afa37496e4b35ae218e1b03e26b607e height=769909 version=0x32bce000 log2_work=93.924929 tx=792623260 date='2023-01-01T19:00:40Z' progress=1.000000 cache=1.3MiB(9604txo)
2023-01-01T19:02:16Z New outbound peer connected: version: 70016, blocks=769909, peer=3 (outbound-full-relay)
2023-01-01T19:02:16Z New outbound peer connected: version: 70016, blocks=769909, peer=4 (outbound-full-relay)
2023-01-01T19:02:18Z P2P peers available. Skipped DNS seeding.
2023-01-01T19:02:18Z dnsseed thread exit
2023-01-01T19:02:23Z New outbound peer connected: version: 70016, blocks=769909, peer=5 (outbound-full-relay)
2023-01-01T19:02:35Z New outbound peer connected: version: 70016, blocks=769909, peer=6 (outbound-full-relay)
2023-01-01T19:08:44Z ThreadRPCServer incorrect password attempt from 127.0.0.1:49244
2023-01-01T19:08:44Z ThreadRPCServer incorrect password attempt from 127.0.0.1:49208
2023-01-01T19:08:44Z New outbound peer connected: version: 70015, blocks=769909, peer=39 (outbound-full-relay)
2023-01-01T19:08:44Z New outbound peer connected: version: 70016, blocks=769909, peer=41 (outbound-full-relay)
2023-01-01T19:08:44Z New outbound peer connected: version: 70015, blocks=769909, peer=43 (outbound-full-relay)
also i read about this libarary NBitcoin but i cannot find simple exmple to use it,
my questions, what are the steps to connect bitcoin core from c#, what is best libarary to use it? how to fix these erros i mention above? is there a simple example of using NBitcoin? Thanks.
a little error ,the word in bitcoin.conf:
rpcpass=mypass
is wrong must be :
rpcpassword=mypass
i change it and it worked fine

How to use WMI to get BOTH the numerical vid/pid and the drive letter from an usb drive

I am trying to show the vid/pid and the drive letter of a usb drive when I connect it to my computer. I'm actually able to do both, but not at the same time.
1: I can use Win32_DiskDrive to get to Win32_LogicalDisk and extract the drive letter. But the deviceId has a non-numerical pid/vid which I can't use.
2: I can use Win32_USBHub or Win32_PnPEntity to extract the vid/pid, but I can't find a link between them and the drive letter.
public void CheckForUsbDevice()
{
string text =
"SELECT * FROM __InstanceCreationEvent " +
"WITHIN 2 "
+ "WHERE TargetInstance ISA 'Win32_PnPEntity'";
ManagementEventWatcher watcher = new ManagementEventWatcher();
WqlEventQuery query = new WqlEventQuery(text);
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();
Console.ReadKey();
}
static readonly Guid GUID_DEVCLASS_USB = new Guid("{36fc9e60-c465-11cf-8056-444553540000}");
static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
if ((new Guid((string)instance["ClassGuid"]) == GUID_DEVCLASS_USB) && ((string)instance.Properties["Name"].Value == "USB Mass Storage Device"))
{
// we're only interested by USB devices, dump all props
foreach (var property in instance.Properties)
{
Console.WriteLine(property.Name + " = " + property.Value);
}
}
}
This has the output:
Availability =
Caption = USB Mass Storage Device
ClassGuid = {36fc9e60-c465-11cf-8056-444553540000}
CompatibleID = System.String[]
ConfigManagerErrorCode = 0
ConfigManagerUserConfig = False
CreationClassName = Win32_PnPEntity
Description = USB Mass Storage Device
DeviceID = USB\VID_0911&PID_1F40&MI_00\6&27CAD51B&0&0000
ErrorCleared =
ErrorDescription =
HardwareID = System.String[]
InstallDate =
LastErrorCode =
Manufacturer = Compatible USB storage device
Name = USB Mass Storage Device
PNPClass = USB
PNPDeviceID = USB\VID_0911&PID_1F40&MI_00\6&27CAD51B&0&0000
PowerManagementCapabilities =
PowerManagementSupported =
Present = True
Service = USBSTOR
Status = OK
StatusInfo =
SystemCreationClassName = Win32_ComputerSystem
SystemName = WINDEV1905EVAL
I need a link between WMI classed containing the numerical pid/vid and the drive letter or a different way how that can be achieved.
I think it might be possible to use DeviceIoControl, but I have no idea where to start there.
Any help is highly appreciated.

How to interconnect C# Socket with ESP8266 (Hardware TCP)

I am trying to create a GUI to an ESP8266 project that I have already developed. The boards are using the NodeMCU firmware, and I am loading programs on through the ESP8266 Arduino Core. I am using C# for my GUI program on Windows.
Here is my debug code for the ESP8266 (in Arduino):
#include <ESP8266WiFi.h>
String ConnectedMAC[8];
IPAddress ConnectedIP[8];
WiFiClient clientforcom;
void setup() {
WiFi.mode(WIFI_AP_STA);
Serial.begin(9600);
int f = WiFi.scanNetworks();
Serial.println("Scanning Networks");
delay(5000);
for (int n = 0; n < f; n++) {
Serial.println(WiFi.SSID(n));
}
WiFi.begin(ssid, passtring); //SSID and passtring are my home network credentials
delay(2000);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.print("The IP of this node is: ");
Serial.println(WiFi.localIP());
}
void loop() {
MACManagement();
WiFiServer serverforclient(WiFi.localIP(), 25565);
while (!serverforclient.hasClient()) { //this does not work with Socket or delay is too long
delay(50);
Serial.println("Waiting for client");
}
clientforcom = serverforclient.available();
while (clientforcom.available() <= 0) {
delay(50);
Serial.println("Waiting for response");
}
String response = clientforcom.readString();
if (response.startsWith("GetController")) {
Serial.println("Sending String");
clientforcom.println("Returned String");
}
}
void MACManagement() {
unsigned char number_client;
struct station_info *stat_info;
struct ip_addr *IPaddress;
IPAddress address;
int i = 0;
number_client = wifi_softap_get_station_num();
stat_info = wifi_softap_get_station_info();
Serial.print(" Total Connected Clients are = ");
Serial.println(number_client);
while (stat_info != NULL) {
IPaddress = &stat_info->ip;
address = IPaddress->addr;
Serial.print("client= ");
Serial.print(i);
Serial.print(" IP adress is = ");
Serial.print((address));
ConnectedIP[i] = address;
Serial.print(" with MAC adress is = ");
Serial.print(stat_info->bssid[0], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[1], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[2], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[3], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[4], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[5], HEX); Serial.print(" ");
ConnectedMAC[i] = String(stat_info->bssid[0], HEX) + ":" + String(stat_info->bssid[1], HEX) + ":" + String(stat_info->bssid[2], HEX) + ":" + String(stat_info->bssid[3], HEX) + ":" + String(stat_info->bssid[4], HEX) + ":" + String(stat_info->bssid[5], HEX);
stat_info = STAILQ_NEXT(stat_info, next);
i++;
Serial.println();
}
}
and here is my network accessing code in C#:
void loadUI(){
enterIPLabel.Visible=false;
errorBox.Text="Connecting to Leader node";
tcpcom=new TcpClient(leadernode.ToString(),25565);
tcpcom.Connect(leadernode.ToString(),25565);
while(!tcpcom.Connected);
tcpcom.Client.Send(System.Text.Encoding.ASCII.GetBytes("GetController"));
errorBox.Text="Awaiting Node Response";
while(tcpcom.Available<=0); //hopefully this should stop this method from executing until the response is made
//FILL IN CODE FOR RETURN STATEMENT
tabController.Visible=true;
NodeMap.Visible=true;
}
However, when I reach the "Waiting for Client" section of the ESP8266 code and I run the C# program, entering the IP Address into leadernode. I get an error from .NET that states:
System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it
I have no idea why the ESP8266 would be refusing the connection, I put delays such that the Software Watch Dog would not initiate, so I don't understand why it would break the program.

I cant get the CMD outputs to display in my textbox.

Since Local User Group Management doesnt seem to be something I can query in C#, I figured I would do a down and dirty version of what I an trying to accomplish and I need some advice for best practices.
THE GOAL:
Essentially, I need to determine if the current local user's password is set to expire and display the result in a textbox. I have already written a text search so I dont mind that there will be extra data sitting on the output since I will distill the data down to a boolean check for one string.
The Problem:
Check out the code below. For some reason the error codes come through from CMD just fine, however, the output does not display in textbox2.
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\').Last(); ;
user.Text = userName;
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = "/c net user";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.Start();
//* Read the output (or the error)
string output = cmd.StandardOutput.ReadToEnd();
textBox2.Text = output;
string err = cmd.StandardError.ReadToEnd();
textBox2.Text = err;
cmd.WaitForExit();
First you're putting the output variable textBox2.Text, then you are replacing the textBox2.Text with err and I believe you're getting nothing from err variable, that's why TextBox2 is not displaying what you're expecting.
try to run the snippet below to check how output and err variable are getting:
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\').Last(); ;
string text = userName;
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = "/c net user";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.Start();
//* Read the output (or the error)
string output = cmd.StandardOutput.ReadToEnd();
string err = cmd.StandardError.ReadToEnd();
Console.WriteLine("Output: "+output );
Console.WriteLine("Err: "+err);
cmd.WaitForExit();
Console.ReadKey();
EDIT
USER_INFO_2
The USER_INFO_2 structure contains information about a user account, including the account name, password data, privilege level, the path to the user's home directory, and other user-related network statistics.
usri2_acct_expires
Specifies a DWORD value that indicates when the account expires. This value is stored as the number of seconds elapsed since 00:00:00, January 1, 1970, GMT. A value of TIMEQ_FOREVER indicates that the account never expires.
from USER_INFO_2 used with NetUserGetInfo.
Declared in Lmaccess.h; include Lm.h.
It is really poor practise to shell to a user commands to do simple things.
Your essential problem and your very silly conclusion that user management isn't available is wrong.
If another program can do something then so can your program.
If you don't know how you look at the API calls it calls (open it in notepad and look - they are alltogether in the file). .NET has it's own WMI class.
C# and C++ and C all have access to WMI. The command line for what you are doing via WMI is
wmic path Win32_Account get /format:list
wmic path Win32_Group get /format:list
wmic path Win32_GroupInDomain get /format:list
wmic path Win32_GroupUser get /format:list
wmic path Win32_SystemAccount get /format:list
wmic path Win32_SystemUsers get /format:list
wmic path Win32_UserAccount get /format:list
For Help
wmic /?
wmic UserAccount /?
wmic useraccount get /?
wmic useraccount set /?
wmic useraccount call /?
The same thing in vbscript is
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_UserAccount")
For Each objItem in colItems
msgbox objitem.Caption & " " & objItem.Description
Next
A C++ example from WDK
#include "querysink.h"
int main(int argc, char **argv)
{
HRESULT hres;
// Step 1: --------------------------------------------------
// Initialize COM. ------------------------------------------
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x"
<< hex << hres << endl;
return 1; // Program has failed.
}
// Step 2: --------------------------------------------------
// Set general COM security levels --------------------------
// Note: If you are using Windows 2000, you need to specify -
// the default authentication credentials for a user by using
// a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
// parameter of CoInitializeSecurity ------------------------
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL // Reserved
);
if (FAILED(hres))
{
cout << "Failed to initialize security. Error code = 0x"
<< hex << hres << endl;
CoUninitialize();
return 1; // Program has failed.
}
// Step 3: ---------------------------------------------------
// Obtain the initial locator to WMI -------------------------
IWbemLocator *pLoc = NULL;
hres = CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator, (LPVOID *) &pLoc);
if (FAILED(hres))
{
cout << "Failed to create IWbemLocator object."
<< " Err code = 0x"
<< hex << hres << endl;
CoUninitialize();
return 1; // Program has failed.
}
// Step 4: -----------------------------------------------------
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = NULL;
// Connect to the local root\cimv2 namespace
// and obtain pointer pSvc to make IWbemServices calls.
hres = pLoc->ConnectServer(
_bstr_t(L"ROOT\\CIMV2"),
NULL,
NULL,
0,
NULL,
0,
0,
&pSvc
);
if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x"
<< hex << hres << endl;
pLoc->Release();
CoUninitialize();
return 1; // Program has failed.
}
cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;
// Step 5: --------------------------------------------------
// Set security levels on the proxy -------------------------
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hres))
{
cout << "Could not set proxy blanket. Error code = 0x"
<< hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1; // Program has failed.
}
// Step 6: --------------------------------------------------
// Use the IWbemServices pointer to make requests of WMI ----
// For example, get the name of the operating system.
// The IWbemService::ExecQueryAsync method will call
// the QuerySink::Indicate method when it receives a result
// and the QuerySink::Indicate method will display the OS name
QuerySink* pResponseSink = new QuerySink();
hres = pSvc->ExecQueryAsync(
bstr_t("WQL"),
bstr_t("SELECT * FROM Win32_OperatingSystem"),
WBEM_FLAG_BIDIRECTIONAL,
NULL,
pResponseSink);
if (FAILED(hres))
{
cout << "Query for operating system name failed."
<< " Error code = 0x"
<< hex << hres << endl;
pSvc->Release();
pLoc->Release();
pResponseSink->Release();
CoUninitialize();
return 1; // Program has failed.
}
// Step 7: -------------------------------------------------
// Wait to get the data from the query in step 6 -----------
Sleep(500);
pSvc->CancelAsyncCall(pResponseSink);
// Cleanup
// ========
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 0; // Program successfully completed.
}
The following code is the header file code for the QuerySink class. The QuerySink class is used in the previous code.
// QuerySink.h
#ifndef QUERYSINK_H
#define QUERYSINK_H
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>
# pragma comment(lib, "wbemuuid.lib")
class QuerySink : public IWbemObjectSink
{
LONG m_lRef;
bool bDone;
CRITICAL_SECTION threadLock; // for thread safety
public:
QuerySink() { m_lRef = 0; bDone = false;
InitializeCriticalSection(&threadLock); }
~QuerySink() { bDone = true;
DeleteCriticalSection(&threadLock); }
virtual ULONG STDMETHODCALLTYPE AddRef();
virtual ULONG STDMETHODCALLTYPE Release();
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,
void** ppv);
virtual HRESULT STDMETHODCALLTYPE Indicate(
LONG lObjectCount,
IWbemClassObject __RPC_FAR *__RPC_FAR *apObjArray
);
virtual HRESULT STDMETHODCALLTYPE SetStatus(
/* [in] */ LONG lFlags,
/* [in] */ HRESULT hResult,
/* [in] */ BSTR strParam,
/* [in] */ IWbemClassObject __RPC_FAR *pObjParam
);
bool IsDone();
};
#endif // end of QuerySink.h
The following code is an implementation of the QuerySink class:
// QuerySink.cpp
#include "querysink.h"
ULONG QuerySink::AddRef()
{
return InterlockedIncrement(&m_lRef);
}
ULONG QuerySink::Release()
{
LONG lRef = InterlockedDecrement(&m_lRef);
if(lRef == 0)
delete this;
return lRef;
}
HRESULT QuerySink::QueryInterface(REFIID riid, void** ppv)
{
if (riid == IID_IUnknown || riid == IID_IWbemObjectSink)
{
*ppv = (IWbemObjectSink *) this;
AddRef();
return WBEM_S_NO_ERROR;
}
else return E_NOINTERFACE;
}
HRESULT QuerySink::Indicate(long lObjectCount,
IWbemClassObject **apObjArray)
{
HRESULT hres = S_OK;
for (int i = 0; i < lObjectCount; i++)
{
VARIANT varName;
hres = apObjArray[i]->Get(_bstr_t(L"Name"),
0, &varName, 0, 0);
if (FAILED(hres))
{
cout << "Failed to get the data from the query"
<< " Error code = 0x"
<< hex << hres << endl;
return WBEM_E_FAILED; // Program has failed.
}
printf("Name: %ls\n", V_BSTR(&varName));
}
return WBEM_S_NO_ERROR;
}
HRESULT QuerySink::SetStatus(
/* [in] */ LONG lFlags,
/* [in] */ HRESULT hResult,
/* [in] */ BSTR strParam,
/* [in] */ IWbemClassObject __RPC_FAR *pObjParam
)
{
if(lFlags == WBEM_STATUS_COMPLETE)
{
printf("Call complete.\n");
EnterCriticalSection(&threadLock);
bDone = true;
LeaveCriticalSection(&threadLock);
}
else if(lFlags == WBEM_STATUS_PROGRESS)
{
printf("Call in progress.\n");
}
return WBEM_S_NO_ERROR;
}
bool QuerySink::IsDone()
{
bool done = true;
EnterCriticalSection(&threadLock);
done = bDone;
LeaveCriticalSection(&threadLock);
return done;
} // end of QuerySink.cpp

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

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;
}
}

Categories