在Linux上使用MONO。
如何使用C#将端口号与服务配对?
示例:
port 80 = http
port 443 = https
并将其输出到控制台,我需要这个用于我构建的简单端口扫描程序。
我知道这个函数存在于ruby中:
Socket.getservbyport(80, "tcp")
答案 0 :(得分:1)
Windows版
更新:看到太晚了,海报在提出问题后添加了Linux和Mono标签,因此写了一个Windows实现。在Linux上,在第二篇文章中使用Mono版本。
穆罕默德的解决方案在很多方面比替代方案更便携。 getservbyname()和getservbyport()是依赖于平台的,需要使用P / Invoke在Windows上使用c#,也很可能在Mono上使用。
要在Mono中实现下面的代码,您需要使用特定于平台的API(标头为netdb.h)进行PInvoke - 请注意,WSAStartUp()和WSACleanUp()是特定于Windows的套接字初始化函数,这些函数无关紧要在Linux系统上。目前没有单声道设置,因此无法提供特定于Linux的解决方案,但如果您愿意跳过这里的箍,那么可以使用Windows(32位)示例来实现代码:
namespace SocketTest
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
[Serializable]
public class SocketUtilException : Exception
{
public SocketUtilException()
{
}
public SocketUtilException(string message)
: base(message)
{
}
public SocketUtilException(string message, Exception inner)
: base(message, inner)
{
}
protected SocketUtilException(
SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
public static class SocketUtil
{
private const int WSADESCRIPTION_LEN = 256;
private const int WSASYSSTATUS_LEN = 128;
[StructLayout(LayoutKind.Sequential)]
public struct WSAData
{
public short wVersion;
public short wHighVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = WSADESCRIPTION_LEN+1)]
public string szDescription;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = WSASYSSTATUS_LEN+1)]
public string wSystemStatus;
[Obsolete("Ignored when wVersionRequested >= 2.0")]
public ushort wMaxSockets;
[Obsolete("Ignored when wVersionRequested >= 2.0")]
public ushort wMaxUdpDg;
public IntPtr dwVendorInfo;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct servent
{
public string s_name;
public IntPtr s_aliases;
public short s_port;
public string s_proto;
}
private static ushort MakeWord ( byte low, byte high)
{
return (ushort)((ushort)(high << 8) | low);
}
[DllImport("ws2_32.dll", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
private static extern int WSAStartup(ushort wVersionRequested, ref WSAData wsaData);
[DllImport("ws2_32.dll", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
private static extern int WSACleanup();
[DllImport("ws2_32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr getservbyname(string name, string proto);
[DllImport("ws2_32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr getservbyport(short port, string proto);
public static string GetServiceByPort(short port, string protocol)
{
var wsaData = new WSAData();
if (WSAStartup(MakeWord(2, 2), ref wsaData) != 0)
{
throw new SocketUtilException("WSAStartup",
new SocketException(Marshal.GetLastWin32Error()));
}
try
{
var netport = Convert.ToInt16(IPAddress.HostToNetworkOrder(port));
var result = getservbyport(netport, protocol);
if (IntPtr.Zero == result)
{
throw new SocketUtilException(
string.Format("Could not resolve service for port {0}", port),
new SocketException(Marshal.GetLastWin32Error()));
}
var srvent = (servent)Marshal.PtrToStructure(result, typeof(servent));
return srvent.s_name;;
}
finally
{
WSACleanup();
}
}
public static short GetServiceByName(string service, string protocol)
{
var wsaData = new WSAData();
if(WSAStartup(MakeWord(2,2), ref wsaData) != 0)
{
throw new SocketUtilException("WSAStartup",
new SocketException(Marshal.GetLastWin32Error()));
}
try
{
var result = getservbyname(service, protocol);
if (IntPtr.Zero == result)
{
throw new SocketUtilException(
string.Format("Could not resolve port for service {0}", service),
new SocketException(Marshal.GetLastWin32Error()));
}
var srvent = (servent)Marshal.PtrToStructure(result, typeof(servent));
return Convert.ToInt16(IPAddress.NetworkToHostOrder(srvent.s_port));
}
finally
{
WSACleanup();
}
}
}
class Program
{
static void Main(string[] args)
{
try
{
var port = SocketUtil.GetServiceByName("http", "tcp");
Console.WriteLine("http runs on port {0}", port);
Console.WriteLine("Reverse call:{0}", SocketUtil.GetServiceByPort(port, "tcp"));
}
catch(SocketUtilException exception)
{
Console.WriteLine(exception.Message);
if(exception.InnerException != null)
{
Console.WriteLine(exception.InnerException.Message);
}
}
}
}
答案 1 :(得分:1)
Mono Linux版
我手上有点时间,所以在我的Ubuntu Linux机器上安装Mono进行测试。 getservbyport()和getservbyname()的Mono PInvoke实现比在Windows上简单(只需加载内置网络内容的libc)。以下是可供参考的示例代码,以防任何人想要它;)
namespace SocketUtil
{
using System;
using System.Net;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
[Serializable]
public class SocketUtilException : Exception
{
public SocketUtilException()
{
}
public SocketUtilException(string message)
: base(message)
{
}
public SocketUtilException(string message, Exception inner)
: base(message, inner)
{
}
protected SocketUtilException(
SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
public static class SocketUtil
{
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct servent
{
public string s_name;
public IntPtr s_aliases;
public ushort s_port;
public string s_proto;
}
[DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr getservbyname(string name, string proto);
[DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr getservbyport(ushort port, string proto);
public static string GetServiceByPort(ushort port, string protocol, out List<string> aliases)
{
var netport = unchecked((ushort)IPAddress.HostToNetworkOrder(unchecked((short)port)));
var result = getservbyport(netport, protocol);
if (IntPtr.Zero == result)
{
throw new SocketUtilException(
string.Format("Could not resolve service for port {0}", port));
}
var srvent = (servent)Marshal.PtrToStructure(result, typeof(servent));
aliases = GetAliases(srvent);
return srvent.s_name;
}
private static List<string> GetAliases(servent srvent)
{
var aliases = new List<string>();
if (srvent.s_aliases != IntPtr.Zero)
{
IntPtr cb;
for (var i = 0;
(cb = Marshal.ReadIntPtr(srvent.s_aliases, i)) != IntPtr.Zero;
i += Marshal.SizeOf(cb))
{
aliases.Add(Marshal.PtrToStringAnsi(cb));
}
}
return aliases;
}
public static ushort GetServiceByName(string service, string protocol, out List<string> aliases)
{
var result = getservbyname(service, protocol);
if (IntPtr.Zero == result)
{
throw new SocketUtilException(
string.Format("Could not resolve port for service {0}", service));
}
var srvent = (servent)Marshal.PtrToStructure(result, typeof(servent));
aliases = GetAliases(srvent);
var hostport = IPAddress.NetworkToHostOrder(unchecked((short)srvent.s_port));
return unchecked((ushort)hostport);
}
}
class Program
{
static void Main(string[] args)
{
try
{
List<string> aliases;
var port = SocketUtil.GetServiceByName("https", "tcp", out aliases);
Console.WriteLine("https runs on port {0}", port);
foreach (var alias in aliases)
{
Console.WriteLine(alias);
}
Console.WriteLine("Reverse call:{0}", SocketUtil.GetServiceByPort(port, "tcp", out aliases));
}
catch (SocketUtilException exception)
{
Console.WriteLine(exception.Message);
if (exception.InnerException != null)
{
Console.WriteLine(exception.InnerException.Message);
}
}
}
}
}
答案 2 :(得分:0)
在Windows上有一个“服务”文件,位于System32 \ Drivers \ Etc \文件夹中。我编写了以下代码来解析它。您可以使用它来查找所需端口的信息:
class Program
{
static void Main(string[] args)
{
var services = ReadServicesFile();
// For example, I want to find information about port 443 of TCP service
var port443Info = services.FirstOrDefault(s => s.Port == 443 && s.Type.Equals("tcp"));
if (port443Info != null)
{
Console.WriteLine("TCP Port = {0}, Service name = {1}", port443Info.Port, port443Info.Name);
}
}
static List<ServiceInfo> ReadServicesFile()
{
var sysFolder = Environment.GetFolderPath(Environment.SpecialFolder.System);
if (!sysFolder.EndsWith("\\"))
sysFolder += "\\";
var svcFileName = sysFolder + "drivers\\etc\\services";
var lines = File.ReadAllLines(svcFileName);
var result = new List<ServiceInfo>();
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line) || line.StartsWith("#"))
continue;
var info = new ServiceInfo();
var index = 0;
// Name
info.Name = line.Substring(index, 16).Trim();
index += 16;
// Port number and type
var temp = line.Substring(index, 9).Trim();
var tempSplitted = temp.Split('/');
info.Port = ushort.Parse(tempSplitted[0]);
info.Type = tempSplitted[1].ToLower();
result.Add(info);
}
return result;
}
}
您还需要以下类声明:
class ServiceInfo
{
public ushort Port { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}