Get MX Records

Posted by on July 17, 2010

This routine will populate an array with the MX records of a given domain name. It’s similar in functionality to getmxrr(); from PHP.

Procedure.i getmxrr( HostName.s, Array MXHosts.s(1) )
 
	Define.s buffer			= ""
	Define.s find_str 		= "mail exchanger = "
	Define.i count			= 0
	Define.i mail_exchanger		= 0
	Define.i find_strlen		= Len(find_str)
	Define.i handle 		= RunProgram( "nslookup", "-type=mx " + HostName, "",  #PB_Program_Open | #PB_Program_Read | #PB_Program_Hide )
 
	If IsProgram( handle )
		While ProgramRunning( handle )
 
			buffer 		= ReadProgramString( handle )
			mail_exchanger 	= FindString( buffer, find_str, 1 )
 
			If mail_exchanger
 
				buffer = Mid( buffer, mail_exchanger + find_strlen, Len(buffer) )
 
				If buffer
					MXHosts(count) = buffer
					count + 1
				EndIf
 
			EndIf
 
		Wend
		CloseProgram( handle )
	EndIf
 
	ProcedureReturn count
 
EndProcedure

This version is Windows only since it’s implemented on top of nslookup. Quite frankly I did not have a need to support other platforms at the time. But hopefully it’ll be useful for someone. For instance if you’re looking to validate an email address, this is the second step after the syntactical validation. (Usually a regular expression is utilized for the first step)

Usage example:

Define.i i	; iteration in case we get a result
Dim mx.s(99)	; this array will become populated with mx records
Define.i result = getmxrr( "google.com", mx() )
 
If result
 
	For i=0 To result - 1
		Debug mx(i)
	Next
 
Else
	Debug "no mx records found"
EndIf

In my case I got the following results:

google.com.s9a2.psmtp.com
google.com.s9b1.psmtp.com
google.com.s9a1.psmtp.com
google.com.s9b2.psmtp.com

Cheers!

0 Comments on Get MX Records

Respond | Trackback

Respond

Comments

Comments:

*