全國最多中醫師線上諮詢網站-台灣中醫網
發文 回覆 瀏覽次數:2466
推到 Plurk!
推到 Facebook!

有辦法得知某隻程式開啟了那些port 嗎???

尚未結案
helliluya
一般會員


發表:5
回覆:7
積分:2
註冊:2003-10-28

發送簡訊給我
#1 引用回覆 回覆 發表時間:2004-01-14 15:28:51 IP:203.70.xxx.xxx 未訂閱
小弟寫了一隻程式,把 netstat -n 的資料抓了回來, Active Connections Proto Local Address Foreign Address State TCP 203.70.xxx.xxx:xxx 63.xxx.xxx.xxx:xxxx ESTABLISHED TCP 203.70.xxx.xxx:xxx 63.xxx.xxx.xxx:xxxx ESTABLISHED 想請問有沒有辦法得知這些port是由那些程式所開啟的 ??? 在此先謝謝各位。
frankiech
中階會員


發表:7
回覆:78
積分:52
註冊:2002-08-29

發送簡訊給我
#2 引用回覆 回覆 發表時間:2004-01-15 09:19:39 IP:61.222.xxx.xxx 未訂閱
有一個Tools : TaskInfo 2003 , 功能很強你可試試看 http://www.iarsn.com/
fangback
初階會員


發表:4
回覆:47
積分:40
註冊:2002-06-15

發送簡訊給我
#3 引用回覆 回覆 發表時間:2004-01-28 12:41:00 IP:61.218.xxx.xxx 未訂閱
在星點子網站有個範例,你可以參考看看。希望對你有幫助... http://netcity1.web.hinet.net/userdata/nep2314/Pages/FreeDL.htm 發表人 - fangback 於 2004/01/28 12:42:19
helliluya
一般會員


發表:5
回覆:7
積分:2
註冊:2003-10-28

發送簡訊給我
#4 引用回覆 回覆 發表時間:2004-02-04 00:17:59 IP:210.68.xxx.xxx 未訂閱
不好意思,過年期間因為回老家關係,沒有電腦可以上網>< 不知道有沒有大大用過 unix 系統下的 sockstat 程式, 我想抓的資料就是像該程式一樣,列出所有在這台電腦上連線的 ip , port , 謝謝各位…
helliluya
一般會員


發表:5
回覆:7
積分:2
註冊:2003-10-28

發送簡訊給我
#5 引用回覆 回覆 發表時間:2004-02-04 06:19:59 IP:203.70.xxx.xxx 未訂閱
小弟應該算是解決這個問題了,    首先小弟用 netstat -o 抓出目前電腦上開啟的 port 和開啟該 port 的 PID ,     如下:    
 
Active Connections      Proto  Local Address          Foreign Address        State           PID
  TCP    xxx:3099               211.167.73.17:http     CLOSE_WAIT      3056
  TCP    xxx:3100               218.30.100.134:http    CLOSE_WAIT      3056    
, 再利用 PID 來找出對應的程式,就解決這個問題了。 想再請教有沒有更聰明一點的方法 ,謝謝。
st
一般會員


發表:11
回覆:21
積分:11
註冊:2004-07-02

發送簡訊給我
#6 引用回覆 回覆 發表時間:2005-09-02 12:25:45 IP:220.135.xxx.xxx 未訂閱
請參考我的 sample    Head File...     
 //---------------------------------------------------------------------------    #ifndef UnitMainH
#define UnitMainH
//---------------------------------------------------------------------------
#include 
#include 
#include 
#include <Forms.hpp>    // This program implements a subset of the Netstat program's
// functionality. Specifically, it enumerates and displays
// information about all UDP and TCP endpoints.
//
//------------------------------------------------------------
#include "windows.h"
#include "stdio.h"
#include "winsock.h"
#include "iprtrmib.h"
#include "tlhelp32.h"
#include "iphlpapi.h"
#include     //---------------------------------------------------------------------------
class TfrmMain : public TForm
{
__published:        // IDE-managed Components
        TButton *cmdRefresh;
        TGroupBox *GroupBox2;
        TListView *ListView1;
        TGroupBox *GroupBox1;
        TListBox *ListBox1;
        void __fastcall cmdRefreshClick(TObject *Sender);
        void __fastcall FormCreate(TObject *Sender);
private:        // User declarations      #define LOCALADDRESS 0x0100007f
  //
  // Maximum string lengths for ASCII ip address and port names
  //
  #define HOSTNAMELEN                256
  #define PORTNAMELEN                256
  #define ADDRESSLEN                HOSTNAMELEN PORTNAMELEN
  #define ANY_SIZE              256
  //
  // Our option flags
  //
  #define FLAG_ALL_ENDPOINTS        1
  #define FLAG_SHOW_NUMBERS        2      //
  // Undocumented extended information structures available
  // only on XP and higher
  //      typedef struct {
    DWORD   dwState;        // state of the connection
    DWORD   dwLocalAddr;    // address on local computer
    DWORD   dwLocalPort;    // port number on local computer
    DWORD   dwRemoteAddr;   // address on remote computer
    DWORD   dwRemotePort;   // port number on remote computer
    DWORD          dwProcessId;
  } MIB_TCPEXROW, *PMIB_TCPEXROW;      typedef struct {
         DWORD                        dwNumEntries;
        MIB_TCPEXROW        table[ANY_SIZE];
  } MIB_TCPEXTABLE, *PMIB_TCPEXTABLE;          typedef struct {
    DWORD   dwLocalAddr;    // address on local computer
    DWORD   dwLocalPort;    // port number on local computer
    DWORD          dwProcessId;
  } MIB_UDPEXROW, *PMIB_UDPEXROW;      typedef struct {
         DWORD                        dwNumEntries;
        MIB_UDPEXROW        table[ANY_SIZE];
  } MIB_UDPEXTABLE, *PMIB_UDPEXTABLE;      //
  // APIs that we link against dynamically in case they aren't
  // present on the system we're running on.
  //
  typedef DWORD (WINAPI *pAllocateAndGetTcpExTableFromStack)(
    PMIB_TCPEXTABLE *pTcpTable,  // buffer for the connection table
    BOOL bOrder,               // sort the table?
    HANDLE heap,
    DWORD zero,
    DWORD flags
  );      pAllocateAndGetTcpExTableFromStack pAllocateAndGetTcpExTableFromStackptr;      typedef DWORD (WINAPI *pAllocateAndGetUdpExTableFromStack)(
    PMIB_UDPEXTABLE *pTcpTable,  // buffer for the connection table
    BOOL bOrder,               // sort the table?
    HANDLE heap,
    DWORD zero,
    DWORD flags
  );      pAllocateAndGetUdpExTableFromStack pAllocateAndGetUdpExTableFromStackptr;      typedef HANDLE (WINAPI *pCreateToolhelp32Snapshot)(
    DWORD dwFlags,
    DWORD th32ProcessID
  );      pCreateToolhelp32Snapshot pCreateToolhelp32Snapshotptr;      typedef BOOL (WINAPI *pProcess32First)(
    HANDLE hSnapshot,
    LPPROCESSENTRY32 lppe
  );      pProcess32First pProcess32Firstptr;      typedef BOOL (WINAPI *pProcess32Next)(
    HANDLE hSnapshot,
    LPPROCESSENTRY32 lppe
  );      pProcess32Next pProcess32Nextptr;      //Variable
  TListColumn  *NewColumn;
  TListItem  *ListItem;
  
  //Functions
  bool ExApisArePresent();
  void PrintError(DWORD ErrorCode);
  PCHAR GetIpHostName(DWORD Flags,BOOL local,UINT ipaddr,PCHAR name,int namelen);
  PCHAR GetPortName(DWORD Flags,UINT port,PCHAR proto,PCHAR name,int namelen);
  PCHAR ProcessPidToName(HANDLE hProcessSnap,DWORD ProcessId,PCHAR ProcessName);    public:                // User declarations
        __fastcall TfrmMain(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TfrmMain *frmMain;
//---------------------------------------------------------------------------
#endif
CPP File....
 //---------------------------------------------------------------------------    #include 
#pragma hdrstop    #include "UnitMain.h"    //---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TfrmMain *frmMain;    //
// Possible TCP endpoint states
//
static char TcpState[][32] = {
        "???",
        "CLOSED",
        "LISTENING",
        "SYN_SENT",
        "SYN_RCVD",
        "ESTABLISHED",
        "FIN_WAIT1",
        "FIN_WAIT2",
        "CLOSE_WAIT",
        "CLOSING",
        "LAST_ACK",
        "TIME_WAIT",
        "DELETE_TCB"
};    int ColumnToSort = 0;    const char tTitle[][20]={"TCP/UDP","Process ID","File Name","State","Local","Remote","Port"};
const int tColWidth[]={80,80,150,150,300,300,100};    //---------------------------------------------------------------------------
__fastcall TfrmMain::TfrmMain(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::FormCreate(TObject *Sender)
{
  //Define ListView
  ListView1->GridLines = true;
  ListView1->HotTrack = true;
  ListView1->RowSelect = true;
  ListView1->ViewStyle = vsReport;
  ListView1->MultiSelect = false;      ListView1->Columns->Clear();
  //Add HeadColumns
  for(int i=0; i <=6; i  )
  {
    NewColumn = ListView1->Columns->Add();
    NewColumn->Caption = tTitle[i];
    NewColumn->Width = tColWidth[i];
    NewColumn->Alignment=taLeftJustify;
  }
}
//--------------------------------------------------------------------------- 
void __fastcall TfrmMain::cmdRefreshClick(TObject *Sender)
{
  DWORD                  error, dwSize;
  WORD                  wVersionRequested;
  WSADATA          wsaData;
  HANDLE          hProcessSnap;
  PMIB_TCPEXTABLE tcpExTable;
  PMIB_TCPTABLE   tcpTable;
  PMIB_UDPEXTABLE udpExTable;
  PMIB_UDPTABLE   udpTable;
  BOOLEAN          exPresent;
  DWORD                  i, flags;
  CHAR                  processName[MAX_PATH];
  CHAR                  localname[HOSTNAMELEN], remotename[HOSTNAMELEN];
  CHAR                  remoteport[PORTNAMELEN], localport[PORTNAMELEN];
  CHAR                  localaddr[ADDRESSLEN], remoteaddr[ADDRESSLEN];      ListView1->Items->Clear();      //
  // Check for NT
  //
  if(GetVersion() >= 0x80000000)
     ListBox1->Items->Add("Requres Windows NT/2K/XP.");
  else
     ListBox1->Items->Add("Windows NT/2K/XP.");      //
  // Initialize winsock
  //
  wVersionRequested = MAKEWORD( 1, 1 );
  if(WSAStartup(wVersionRequested, &wsaData))
     ListBox1->Items->Add("Could not initialize Winsock.");
  else
     ListBox1->Items->Add("Initialize Winsock.");      //
  // Get options
  //
  exPresent = ExApisArePresent();      //
  // Determine if extended query is available (it's only present
  // on XP and higher).
  //
  if(exPresent)
  {
    //
    // Get the tables of TCP and UDP endpoints with process IDs
    //
    error = pAllocateAndGetTcpExTableFromStackptr(&tcpExTable, true, GetProcessHeap(), 2, 2 );        if(error)
    {
      ListBox1->Items->Add("Failed to snapshot TCP endpoints.");
      PrintError(error);
    }
    error = pAllocateAndGetUdpExTableFromStackptr(&udpExTable, true, GetProcessHeap(), 2, 2 );
    if(error)
    {
      ListBox1->Items->Add("Failed to snapshot UDP endpoints.");
      PrintError(error);
    }        //
    // Get a process snapshot. Note that we won't be guaranteed to
    // exactly match a PID against a process name because a process could have exited
    // and the PID gotten reused between our endpoint and process snapshots.
    //
    hProcessSnap = pCreateToolhelp32Snapshotptr(TH32CS_SNAPPROCESS,0);
    if( hProcessSnap == INVALID_HANDLE_VALUE )
    {
      ListBox1->Items->Add("Failed to take process snapshot. Process names will not be shown.");
    }        //
    // Dump the TCP table
    //
    for( i = 0; i < tcpExTable->dwNumEntries; i   )
    {
      if( flags & FLAG_ALL_ENDPOINTS || tcpExTable->table[i].dwState == MIB_TCP_STATE_ESTAB )
      {
        sprintf(localaddr, "%s:%s",
          GetIpHostName( flags, TRUE, tcpExTable->table[i].dwLocalAddr, localname, HOSTNAMELEN),
          GetPortName( flags, tcpExTable->table[i].dwLocalPort, "tcp", localport, PORTNAMELEN ));            sprintf( remoteaddr, "%s:%s",
          GetIpHostName( flags, FALSE, tcpExTable->table[i].dwRemoteAddr, remotename, HOSTNAMELEN),
                          tcpExTable->table[i].dwRemoteAddr ?
          GetPortName( flags, tcpExTable->table[i].dwRemotePort, "tcp", remoteport, PORTNAMELEN ):
                          "0" );            ListBox1->Items->Add("TCP");
        ListBox1->Items->Add(ProcessPidToName(hProcessSnap,tcpExTable->table[i].dwProcessId,processName));
        ListBox1->Items->Add(TcpState[tcpExTable->table[i].dwState]);
        ListBox1->Items->Add(tcpExTable->table[i].dwProcessId);
        ListBox1->Items->Add(localaddr);
        ListBox1->Items->Add(remoteaddr);
        ListBox1->Items->Add(localport);            ListItem = ListView1->Items->Add();
        ListItem->Caption = "TCP";
        ListItem->SubItems->Add(tcpExTable->table[i].dwProcessId);
        ListItem->SubItems->Add(ProcessPidToName(hProcessSnap,tcpExTable->table[i].dwProcessId,processName));
        ListItem->SubItems->Add(TcpState[tcpExTable->table[i].dwState]);
        ListItem->SubItems->Add(localaddr);
        ListItem->SubItems->Add(remoteaddr);
        ListItem->SubItems->Add(localport);
      }
    }
    //
    // Dump the UDP table
    //
    if( flags & FLAG_ALL_ENDPOINTS )
    {
      for( i = 0; i < udpExTable->dwNumEntries; i   )
      {
               sprintf( localaddr, "%s:%s",
          GetIpHostName( flags, TRUE, udpExTable->table[i].dwLocalAddr, localname, HOSTNAMELEN),
          GetPortName( flags, udpExTable->table[i].dwLocalPort, "tcp", localport, PORTNAMELEN ));
                    ListBox1->Items->Add("DUP");
        ListBox1->Items->Add(udpExTable->table[i].dwProcessId);
        ListBox1->Items->Add(ProcessPidToName(hProcessSnap, udpExTable->table[i].dwProcessId, processName ));
        ListBox1->Items->Add("");
        ListBox1->Items->Add(localaddr);
        ListBox1->Items->Add("*.*.*.*:*");  
        ListBox1->Items->Add(localport);            ListItem = ListView1->Items->Add();
        ListItem->Caption = "UDP";
        ListItem->SubItems->Add(udpExTable->table[i].dwProcessId);
        ListItem->SubItems->Add(ProcessPidToName(hProcessSnap, udpExTable->table[i].dwProcessId, processName ));
        ListItem->SubItems->Add("");
        ListItem->SubItems->Add(localaddr);
        ListItem->SubItems->Add("*.*.*.*:*");
        ListItem->SubItems->Add(localport);
      }
    }
  }
}
//---------------------------------------------------------------------------
//--------- PRIVATE FUNCTIONS -----------------------------------------------
//---------------------------------------------------------------------------
bool TfrmMain::ExApisArePresent()
{
  pAllocateAndGetTcpExTableFromStackptr =(pAllocateAndGetTcpExTableFromStack) GetProcAddress(LoadLibrary("iphlpapi.dll"),"AllocateAndGetTcpExTableFromStack");      if(!pAllocateAndGetTcpExTableFromStackptr ) return false;      pAllocateAndGetUdpExTableFromStackptr = (pAllocateAndGetUdpExTableFromStack) GetProcAddress( LoadLibrary( "iphlpapi.dll"),"AllocateAndGetUdpExTableFromStack");
  if(!pAllocateAndGetUdpExTableFromStackptr ) return false;      pCreateToolhelp32Snapshotptr = (pCreateToolhelp32Snapshot) GetProcAddress(GetModuleHandle("kernel32.dll"),"CreateToolhelp32Snapshot");
  if(!pCreateToolhelp32Snapshotptr ) return false;      pProcess32Firstptr = (pProcess32First) GetProcAddress(GetModuleHandle( "kernel32.dll" ),"Process32First" );
  if(!pProcess32Firstptr ) return false;      pProcess32Nextptr = (pProcess32Next) GetProcAddress( GetModuleHandle( "kernel32.dll" ),"Process32Next" );
  if(!pProcess32Nextptr ) return false;      return true;    /*
typedef BOOL (WINAPI* API_Win32NLSEnableIME)(HWND hWnd,BOOL Enable);    API_Win32NLSEnableIME API_Win32NLSEnableIMEPtr=NULL;
HMODULE HModule=::GetModuleHandle("USER32.DLL");
if(NULL==HModule)
            HModule=::LoadLibrary("USER32.DLL");
if(HModule)
           API_Win32NLSEnableIMEPtr=(API_Win32NLSEnableIME)::GetProcAddress(HModule,"Win32NLSEnableIME");
if(NULL!=API_Win32NLSEnableIMEPtr)
         return API_Win32NLSEnableIMEPtr(hWnd,Enable);
*/
}
//---------------------------------------------------------------------------
//
// PrintError
// 
// Translates a Win32 error into a text equivalent
//
void TfrmMain::PrintError(DWORD ErrorCode)
{
  LPTSTR lpMsgBuf;      FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                                        NULL, ErrorCode, 
                                        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                                        (LPTSTR) &lpMsgBuf, 0, NULL );
  ListBox1->Items->Add(lpMsgBuf);
  LocalFree(lpMsgBuf);
}
//---------------------------------------------------------------------------
//
// GetIpHostName
//
// Translate IP addresses into their name-resolved form
// if possible.
//
PCHAR TfrmMain::GetIpHostName(DWORD Flags,BOOL local,UINT ipaddr,PCHAR name,int namelen)
{
  struct hostent *phostent;
  UINT        nipaddr;      //
  // Does the user want raw numbers?
  //
  nipaddr = htonl( ipaddr );
  if( Flags & FLAG_SHOW_NUMBERS )
  {
    sprintf( name, "%d.%d.%d.%d",
            (nipaddr >> 24) & 0xFF,
            (nipaddr >> 16) & 0xFF,
            (nipaddr >> 8) & 0xFF,
            (nipaddr) & 0xFF);        return name;
  }      //
  // Try to translate to a name
  //
  if(!ipaddr)
  {
    if(!local)
    {
      sprintf(name, "%d.%d.%d.%d",
           (nipaddr >> 24) & 0xFF,
           (nipaddr >> 16) & 0xFF,
           (nipaddr >> 8) & 0xFF,
           (nipaddr) & 0xFF);
    }
    else
    {
      gethostname(name, namelen);
    }      }
  else if( ipaddr == LOCALADDRESS )
  {
    if( local )
    {
      gethostname(name, namelen);
    }
    else
    {
      strcpy(name, "localhost" );
    }
  }
  else if(phostent = gethostbyaddr( (char *) &ipaddr,sizeof( nipaddr ), PF_INET ))
  {
    strcpy( name, phostent->h_name );
  }
  else
  {
    sprintf( name, "%d.%d.%d.%d",
            (nipaddr >> 24) & 0xFF,
        (nipaddr >> 16) & 0xFF,
        (nipaddr >> 8) & 0xFF,
        (nipaddr) & 0xFF);
  }      return name;
}
//---------------------------------------------------------------------------
//
// GetPortName
//
// Translate port numbers into their text equivalent if 
// there is one
//
PCHAR TfrmMain::GetPortName(DWORD Flags,UINT port,PCHAR proto,PCHAR name,int namelen)
{
  struct servent *psrvent;      if(Flags & FLAG_SHOW_NUMBERS )
  {
     sprintf( name, "%d", htons( (WORD) port));
     return name;
  }      //
  // Try to translate to a name
  //
  if( psrvent = getservbyport(port, proto))
  {
    strcpy(name, psrvent->s_name);
  }
  else
  {
    sprintf(name, "%d", htons((WORD) port));
  }
  return name;
}
//---------------------------------------------------------------------------
//
// ProcessPidToName
//
// Translates a PID to a name.
//
PCHAR TfrmMain::ProcessPidToName(HANDLE hProcessSnap,DWORD ProcessId,PCHAR ProcessName)
{
  PROCESSENTRY32 processEntry;      processEntry.dwSize = sizeof( processEntry );
  strcpy( ProcessName, "???" );      if(!pProcess32Firstptr(hProcessSnap,&processEntry))
  {
    return ProcessName;
  }      do
  {
    if( processEntry.th32ProcessID == ProcessId )
    {
      strcpy( ProcessName, processEntry.szExeFile );
      return ProcessName;
    }
  } while( pProcess32Nextptr( hProcessSnap, &processEntry ));        return ProcessName;
}
//---------------------------------------------------------------------------    
寫程式與攝影一樣重要
系統時間:2024-04-24 12:14:43
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!